使用 python 将带有换行符的列表写入文件
如何将带有换行符的列表写入文件中?writelines() 函数无法插入换行符。
解决方法:
-
使用循环:
立即学习“Python免费学习笔记(深入)”;
with open('file.txt', 'w') as f: for line in lines: f.write(f"{line} ")
-
对于 python
with open('file.txt', 'w') as f: for line in lines: f.write("%s " % 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} ")