Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a list of strings to a file in a single line? - Python

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
like image 218
alvas Avatar asked Jan 19 '26 11:01

alvas


1 Answers

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.

like image 78
Ford Avatar answered Jan 22 '26 00:01

Ford