我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:

f.writelines([f"{line}\n" for line in lines])

当前回答

我最近发现Path很有用。帮助我绕过不得不打开('file')作为f,然后写入文件。希望这对某些人有用:)。

from pathlib import Path
import json
a = [[1,2,3],[4,5,6]]
# write
Path("file.json").write_text(json.dumps(a))
# read
json.loads(Path("file.json").read_text())

其他回答

序列化列表到文本文件与逗号分隔值

mylist = dir()
with open('filename.txt','w') as f:
    f.write( ','.join( mylist ) )

还有另一种方式。使用simplejson序列化为json(在python 2.6中包含为json):

>>> import simplejson
>>> f = open('output.txt', 'w')
>>> simplejson.dump([1,2,3,4], f)
>>> f.close()

如果你检查output.txt:

[1, 2, 3, 4]

这很有用,因为它的语法是python的,它是人类可读的,并且它可以被其他语言的其他程序读取。

你打算怎么处理这个文件?这个文件是否存在于人类,或其他具有明确互操作性要求的程序?

如果您只是试图将列表序列化到磁盘,以便稍后由同一python应用程序使用,则应该pickle该列表。

import pickle

with open('outfile', 'wb') as fp:
    pickle.dump(itemlist, fp)

再读一遍:

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)

在一般情况下

下面是writelines()方法的语法

fileObject.writelines( sequence )

例子

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
seq = ["This is 6th line\n", "This is 7th line"]

# Write sequence of lines at the end of the file.
line = fo.writelines( seq )

# Close opend file
fo.close()

参考

http://www.tutorialspoint.com/python/file_writelines.htm

设avg为列表,则:

In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')

您可以根据自己的需求使用%e或%s。