Search code examples
pythonfilelistfile-ionewline

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

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.