有沒有辦法在一行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
有沒有辦法在一行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
兩行:
lines = [ ... ]
with open('sometextfile', 'a') as outfile:
outfile.write('\n'.join(lines) + '\n')
我們在最後一個結尾的新行添加\n
。
一號線:
lines = [ ... ]
open('sometextfile', 'a').write('\n'.join(lines) + '\n')
我主張雖然與第一去。
而不是重新打開文件,每寫,你可以
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」。
看起來這是我們最接近的一行。 – alvas