Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Writing a list to a file with Python, with newlines

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])

Answer*

Cancel
2
  • 37
    No trailing newline, uses 2x space compared to the loop.
    – Dave
    Commented May 22, 2009 at 18:13
  • Have not benchmarked anything, but I guess this is much faster for big lists than looping through every item and writing each line.
    – skranz
    Commented Apr 22 at 8:05