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

alv*_*vas 2 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
Run Code Online (Sandbox Code Playgroud)

For*_*ord 6

两行:

lines = [ ... ]

with open('sometextfile', 'a') as outfile:
    outfile.write('\n'.join(lines) + '\n')
Run Code Online (Sandbox Code Playgroud)

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

一条线:

lines = [ ... ]
open('sometextfile', 'a').write('\n'.join(lines) + '\n')
Run Code Online (Sandbox Code Playgroud)

不过,我会争辩说第一个。