在一行中将字符串列表附加到文件中? - Python

时间:2013-07-17 08:01:55

标签: python string file append output

有没有办法在一行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 个答案:

答案 0 :(得分:3)

两行:

lines = [ ... ]

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

我们在末尾添加\n作为尾随换行符。

一行:

lines = [ ... ]
open('sometextfile', 'a').write('\n'.join(lines) + '\n')

我想争论第一个。

答案 1 :(得分: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”。

答案 2 :(得分:-1)

你可以这样做:

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))