HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

Writing a list to a file with Python, with newlines

Submitted by: @import:stackoverflow-api··
0
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:

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, line


If 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, line

Context

Stack Overflow Q#899103, score: 1359

Revisions (0)

No revisions yet.