Home > Backend Development > Python Tutorial > Why Do My Python-Generated CSV Files Have Blank Lines Between Rows?

Why Do My Python-Generated CSV Files Have Blank Lines Between Rows?

Patricia Arquette
Release: 2024-12-14 15:14:11
Original
537 people have browsed it

Why Do My Python-Generated CSV Files Have Blank Lines Between Rows?

CSV Files Generated by Python Have Blank Lines Between Rows

This question arises when writing CSV files using Python's csv module and encountering additional blank lines between each record when opening the resulting file in Microsoft Excel.

Cause:

The csv.writer module directly controls line endings and inserts "rn" into the file. In Python 3, files should be opened in untranslated text mode with the parameters 'w', newline='', to prevent writing "rrn" on Windows, where the default text mode translates each "n" to "rn."

Solution:

Python 3:

with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)
Copy after login

Python 3 with pathlib:

from pathlib import Path
import csv

with Path('/pythonwork/thefile_subset11.csv').open('w', newline='') as outfile:
    writer = csv.writer(outfile)
Copy after login

Python 2:

Open outfile in binary mode with 'wb' instead of 'w':

with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
    writer = csv.writer(outfile)
Copy after login

Note:

  • In Python 2, writing Unicode strings to CSVs requires additional workarounds.
  • The unicodecsv module provides an alternative for handling Unicode in Python 2.
  • For documentation, refer to the links provided in the answer.

The above is the detailed content of Why Do My Python-Generated CSV Files Have Blank Lines Between Rows?. 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