2013-07-17 69 views
1

有沒有辦法在一行python代碼中追加一行文件到一個文件?我一直在做它是這樣:將字符串列表追加到單行文件中? - 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

兩行:

lines = [ ... ] 

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

我們在最後一個結尾的新行添加\n

一號線:

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

我主張雖然與第一去。

+0

看起來這是我們最接近的一行。 – alvas

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

append not write =) – alvas

+0

@ 2er0如果你需要附加yes(即如果文件中已經有東西),但是使用這個解決方案,你可以一次寫入整個緩衝區,所以沒關係。 – 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) 

您可能還需要添加一個空格,如「延繩釣=延繩釣+‘’+ 1」。

相關問題