Python Forum

Full Version: print a line break in writelines() method
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
lines=["Line 1","Line 2"]
f=open(r"C:\Users\....\Documents\somefile.txt","w")
f.writelines(lines)
f.close()


How to print a line breaker between items in lines variable (list) when placing them in the text file?
First: Use a context manager. It closes your file automatically, when the block is left.

with open(r"C:\Users\....\Documents\somefile.txt", "w") as fd:
    for line in lines:
        fd.write(line)
        fd.write("\n")
Doing this with writelines can be done with a trick:
from itertools import repeat, chain


with open(r"C:\Users\....\Documents\somefile.txt", "w") as fd:
    line_sep = repeat("\n")
    line_iter = chain.from_iterable(zip(lines, line_sep))
    fd.writelines(line_iter)