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

Why Does My Python CSV Output Have Extra Carriage Returns on Windows?

Patricia Arquette
Release: 2024-12-03 19:30:13
Original
481 people have browsed it

Why Does My Python CSV Output Have Extra Carriage Returns on Windows?

CSV Output File Additional Carriage Return Issue on Windows in Python

When generating CSV files in Python, it's possible to inadvertently add an extra carriage return at the end of each row. This behavior can be observed in the following code:

import csv

with open('test.csv', 'w') as outfile:
    writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(['hi', 'dude'])
    writer.writerow(['hi2', 'dude2'])
Copy after login

Expected Output:

hi,dude
hi2,dude2
Copy after login

Actual Output (Windows):

hi,dude\r\r\nhi2,dude2\r\r\n
Copy after login

Causes and Resolution for Python 3:

In Python 3, this issue arises because of the default universal newline translation feature. To resolve it, open the file with newline='' to disable this translation:

with open('output.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    ...
Copy after login

Causes and Resolution for Python 2:

On Windows in Python 2, this issue occurs because CSV is considered a binary format, and rn is the record separator. If the file is opened in text mode, Python replaces the n with rn, resulting in the double carriage return. The solution is to always open files in binary mode:

with open('test.csv', 'wb') as outfile:
    writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    ...
Copy after login

The above is the detailed content of Why Does My Python CSV Output Have 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