将字符串列表附加到一行中的文件?-python
有没有一种方法可以在python代码行中将行列表附加到文件中?我一直在这样做:将字符串列表附加到一行中的文件?-python,python,string,file,append,output,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 你可以这样做: lines = ['this is the foo bar line to append','this i
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 = ['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))
不必每次写入都重新打开文件,您可以
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”中所示 两行:
lines = [ ... ]
with open('sometextfile', 'a') as outfile:
outfile.write('\n'.join(lines) + '\n')
我们在尾随换行符的末尾添加\n
一行:
lines = [ ... ]
open('sometextfile', 'a').write('\n'.join(lines) + '\n')
不过,我还是赞成第一种方法。@2er0如果您需要附加yes(即,如果文件中已经有内容),但是使用此解决方案,您可以一次写入整个缓冲区,所以这无关紧要。似乎这是最接近一行的方法。