如何在Python中将一个字符串列表一行代码添加到文件末尾?

3
有没有一种方法可以在一行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
3个回答

9

两行:

lines = [ ... ]

with open('sometextfile', 'a') as outfile:
    outfile.write('\n'.join(lines) + '\n')

我们在结尾添加\n来增加一个换行符。
一行代码:
lines = [ ... ]
open('sometextfile', 'a').write('\n'.join(lines) + '\n')

我会建议选择第一个选项。

似乎这是我们能得到的最接近一行代码的方式。 - alvas

0
你可以这样做:
lines = ['this is the foo bar line to append','this is the second line', 'whatever third line']

with open('file.txt', 'w') as fd:
    fd.write('\n'.join(lines))

@2er0 如果你需要添加是的话(即如果文件中已经有内容),但是使用这个解决方案,你可以一次性写入整个缓冲区,所以不用担心。 - Unda

0

不要在每次写入时重新打开文件,可以使用

lines = ['this is the foo bar line to append','this is the second line', 'whatever third line']

out = open('filename','a')
for l in lines:
  out.write(l)

这将会将它们每行写入一个新的行。如果您想要它们在一行上,您可以

lines = ['this is the foo bar line to append','this is the second line', 'whatever third line']

out = open('filename','a')
for l in lines:
  longline = longline + l
out.write(longline)

你可能还想添加一个空格,例如 "longline = longline + ' ' + l"。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接