all Python 3Files & I/Ofunction
io.IOBase.writelines()
writing
Write every string from an iterable in sequence; it adds no separators, so '\n' must already be in the strings or everything runs together.
Syntax
f.writelines(lines)
The name misleads: the method knows nothing about "lines", it just calls write() on each item in turn. It pairs with readlines(), which keeps the '\n' inside each item, so f_out.writelines(f_in.readlines()) keeps the line structure (byte for byte only in binary mode: text mode turns '\r\n' into '\n' on reading) — but after splitlines() or strip() you have to put the newlines back yourself. Any iterable works as input, including a generator or another file object; in binary mode the items must be bytes or you get a TypeError.
Examples
lines = ['line1\n', 'line2\n', 'line3\n']
with open('out2.txt', 'w') as f:
f.writelines(lines)
with open('out3.txt', 'w') as f:
f.writelines(f'{i}\n' for i in range(5))
See also
Open in the full glossarydocs.python.orgReport an inaccuracy