The following code adds an extra blank line ("\r") to every write, whereas it is supposed to just write one ("\r\n") at the end of every write. I have no idea why.
import os
with open("output", "w", encoding="utf-8") as f:
for i in range(10):
f.write(str(i) + os.linesep)
It writes to the file: "0\r\r\n1\r\r\n2...9\r\r\n". I am using Python 3.9.16 on Windows. Am I missing something here?
Edit: I tested without encoding="utf-8" as well, and still the same issue happens.
You don't need to use os.linesep
directly. Opening a file for writing in text mode already does newline translation unless you specify a newline
setting that turns it off.
In fact, the os.linesep
docs specifically warn you not to do this:
Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single
'\n'
instead, on all platforms.