我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
当前回答
因为我很懒....
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:
list(map(lambda item : f.write("%s\n" % item),my_list))
更简单的是:
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")
如果在python3上,还可以使用print函数,如下所示。
f = open("myfile.txt","wb")
print(mylist, file=f)
我想你在寻找这样的答案。
f = open('output.txt','w')
list = [3, 15.2123, 118.3432, 98.2276, 118.0043]
f.write('a= {:>3d}, b= {:>8.4f}, c= {:>8.4f}, d= {:>8.4f}, e=
{:>8.4f}\n'.format(*list))
f.close()