Home >Backend Development >Python Tutorial >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)
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)
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)
Note:
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!