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

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

当前回答

简单:

with open("text.txt", 'w') as file:
    file.write('\n'.join(yourList))

其他回答

更简单的是:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(itemlist))

要确保项目列表中的所有项目都是字符串,请使用生成器表达式:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(str(item) for item in itemlist))

记住,项目列表占用内存,所以要注意内存消耗。

另一种迭代和添加换行符的方法:

for item in items:
    filewriter.write(f"{item}" + "\n")

因为我很懒....

import json
a = [1,2,3]
with open('test.txt', 'w') as f:
    f.write(json.dumps(a))

#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
    a = json.loads(f.read())

使用循环:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write(f"{line}\n")

对于Python <3.6:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write("%s\n" % line)

对于Python 2,还可以使用:

with open('your_file.txt', 'w') as f:
    for line in lines:
        print >> f, line

如果您热衷于单个函数调用,至少要删除方括号[],以便每次生成一个要打印的字符串(genexp而不是listcomp)——没有理由占用物化整个字符串列表所需的所有内存。

还有另一种方式。使用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的,它是人类可读的,并且它可以被其他语言的其他程序读取。