
使用 python 将带有换行符的列表写入文件
如何将带有换行符的列表写入文件中?writelines() 函数无法插入换行符。
解决方法:
-
使用循环:
立即学习“Python免费学习笔记(深入)”;
with open('file.txt', 'w') as f: for line in lines: f.write(f"{line}\n") -
对于 python
with open('file.txt', 'w') as f: for line in lines: f.write("%s\n" % line) -
对于 python 2:
with open('file.txt', 'w') as f: for line in lines: print >> f, line -
单个函数调用:
为了减少内存占用,可以删除方括号以逐个写入字符串。
with open('file.txt', 'w') as f: for line in lines: f.write(f"{line}\n")










