2

有没有办法在一行 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
4

3 回答 3

6

两行:

lines = [ ... ]

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

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

一条线:

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

不过,我会主张选择第一个。

于 2013-07-17T13:12:19.270 回答
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))
于 2013-07-17T11:00:39.707 回答
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”。

于 2013-07-17T11:09:11.147 回答