Home > Backend Development > Python Tutorial > Why Does My Python CSV Writer Add Extra Carriage Returns on Windows?

Why Does My Python CSV Writer Add Extra Carriage Returns on Windows?

Linda Hamilton
Release: 2024-12-07 02:14:11
Original
329 people have browsed it

Why Does My Python CSV Writer Add Extra Carriage Returns on Windows?

CSV in Python Appends an Extra Carriage Return on Windows

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
Copy after login

The file reads as:

hi,dude\r
\r
hi2,dude2\r
\r
Copy after login

This behavior arises due to platform-specific line termination handling.

Python 3

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)
    # ...
Copy after login

By default, the CSV writer terminates each line with 'rn', per RFC 4180.

Python 2

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template