我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
当前回答
将stdout重定向到一个文件也可以用于此目的:
from contextlib import redirect_stdout
with open('test.txt', 'w') as f:
with redirect_stdout(f):
for i in range(mylst.size):
print(mylst[i])
其他回答
你打算怎么处理这个文件?这个文件是否存在于人类,或其他具有明确互操作性要求的程序?
如果您只是试图将列表序列化到磁盘,以便稍后由同一python应用程序使用,则应该pickle该列表。
import pickle
with open('outfile', 'wb') as fp:
pickle.dump(itemlist, fp)
再读一遍:
with open ('outfile', 'rb') as fp:
itemlist = pickle.load(fp)
使用循环:
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)——没有理由占用物化整个字符串列表所需的所有内存。
序列化列表到文本文件与逗号分隔值
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))
记住,项目列表占用内存,所以要注意内存消耗。
在一般情况下
下面是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