有没有办法将行列表 append 到Python代码行中的文件中?我一直这样做:
lines = ['this is the foo bar line to append','this is the second line', 'whatever third line']
for l in lines:
print>>open(infile,'a'), l
最佳答案
两行:
lines = [ ... ]
with open('sometextfile', 'a') as outfile:
outfile.write('\n'.join(lines) + '\n')
我们在末尾添加 \n
作为尾随换行符。
一行:
lines = [ ... ]
open('sometextfile', 'a').write('\n'.join(lines) + '\n')
尽管如此,我还是赞成选择第一个。
关于python - 在单行中将字符串列表 append 到文件中? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17694340/