The code snippet provided generates a CSV file with an unexpected extra carriage return (r) on each row. Instead of the desired output:
hi,dude hi2,dude2
The file reads as:
hi,dude\r \r hi2,dude2\r \r
This behavior arises due to platform-specific line termination handling.
The official CSV documentation suggests using newline='' when opening files to disable universal newlines translation:
with open('output.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) # ...
By default, the CSV writer terminates each line with 'rn', per RFC 4180.
On Windows, files should be opened in binary mode ("rb" or "wb") before passing them to csv.reader or csv.writer. Although CSV is a text format, it's considered binary by the involved libraries, with 'rn' separating records. When written in text mode, the Python runtime replaces 'n' with 'rn', resulting in the observed extra carriage returns.
The above is the detailed content of Why Does My Python CSV Writer Add Extra Carriage Returns on Windows?. For more information, please follow other related articles on the PHP Chinese website!