Is there a way to append a list of lines to a file in a line of python code? I've been doing it as such:
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
Two lines:
lines = [ ... ]
with open('sometextfile', 'a') as outfile:
outfile.write('\n'.join(lines) + '\n')
We add the \n at the end for a trailing newline.
One line:
lines = [ ... ]
open('sometextfile', 'a').write('\n'.join(lines) + '\n')
I'd argue for going with the first though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With