CSV File Written with Python Contains Blank Lines Between Rows
When writing a CSV file in Python, you may encounter blank lines between each row when opening it in Microsoft Excel. This issue arises because the csv.writer module controls line endings, writing "rn" into the file.
Solutions for Python 3:
To eliminate the blank lines, rewrite the code to open the output file with newline=''. This parameter prevents any newline translation, ensuring that only "n" is written, resulting in a single line per row.
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile: writer = csv.writer(outfile)
Alternatively, you can use the Path module's open method with newline=''.
from pathlib import Path with Path('/pythonwork/thefile_subset11.csv').open('w', newline='') as outfile: writer = csv.writer(outfile)
Solutions for Python 2:
For Python 2, use binary mode by opening the output file with 'wb' instead of 'w'.
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile: writer = csv.writer(outfile)
Additional Notes:
The above is the detailed content of Why Are There Blank Lines in My Python-Written CSV File When Opened in Excel?. For more information, please follow other related articles on the PHP Chinese website!