patternpythonCritical
Writing a list to a file with Python, with newlines
Viewed 0 times
listpythonnewlinesfilewritingwith
Problem
How do I write a list to a file?
writelines() doesn't insert newline characters, so I need to do:f.writelines([f"{line}\n" for line in lines])Solution
Use a loop:
For Python <3.6:
For Python 2, one may also use:
If you're keen on a single function call, at least remove the square brackets
with open('your_file.txt', 'w') as f:
for line in lines:
f.write(f"{line}\n")For Python <3.6:
with open('your_file.txt', 'w') as f:
for line in lines:
f.write("%s\n" % line)For Python 2, one may also use:
with open('your_file.txt', 'w') as f:
for line in lines:
print >> f, lineIf you're keen on a single function call, at least remove the square brackets
[], so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.Code Snippets
with open('your_file.txt', 'w') as f:
for line in lines:
f.write(f"{line}\n")with open('your_file.txt', 'w') as f:
for line in lines:
f.write("%s\n" % line)with open('your_file.txt', 'w') as f:
for line in lines:
print >> f, lineContext
Stack Overflow Q#899103, score: 1359
Revisions (0)
No revisions yet.