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

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

当前回答

使用Python 3和Python 2.6+语法:

with open(filepath, 'w') as file_handler:
    for item in the_list:
        file_handler.write("{}\n".format(item))

这是平台独立的。它还使用换行符结束最后一行,这是UNIX的最佳实践。

从Python 3.6开始,"{}\n".format(item)可以用f-string替换:f"{item}\n"。

其他回答

我建议这个解决方案。

with open('your_file.txt', 'w') as f:        
    list(map(lambda item : f.write("%s\n" % item),my_list))   

在一般情况下

下面是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

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

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

更简单的是:

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))

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

with open ("test.txt","w")as fp:
   for line in list12:
       fp.write(line+"\n")