
如何将带有换行符的列表写入文件
在 python 中,使用 writelines() 方法将列表中的字符串写入文件时,无法插入换行符。要实现此目的,可以使用以下方法:
使用循环:
with open('your_file.txt', 'w') as f:
for line in lines:
f.write(f"{line}\n")对于 python <3.6:
立即学习“Python免费学习笔记(深入)”;
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也可以使用单个函数调用,但需要删除方括号 [] 以一次打印一个字符串:
with open('your_file.txt', 'w') as f:
for line in (f"{line}\n" for line in lines):
f.write(line)










