我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
当前回答
另一种迭代和添加换行符的方法:
for item in items:
filewriter.write(f"{item}" + "\n")
其他回答
使用循环:
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)——没有理由占用物化整个字符串列表所需的所有内存。
我建议这个解决方案。
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
在Python 3中,你可以使用print和*进行参数解包:
with open("fout.txt", "w") as fout:
print(*my_list, sep="\n", file=fout)
with open ("test.txt","w")as fp:
for line in list12:
fp.write(line+"\n")