CSV file written with Python has blank lines between each row

In Python 2, open outfile with mode 'wb' instead of 'w'. The csv.writer writes \r\n into the file directly. If you don’t open the file in binary mode, it will write \r\r\n because on Windows text mode will translate each \n into \r\n.

In Python 3 the required syntax changed and the csv module now works with text mode 'w', but also needs the newline="" (empty string) parameter to suppress Windows line translation (see documentation links below).

Examples:

# Python 2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
    writer = csv.writer(outfile)

# Python 3
with open('/pythonwork/thefile_subset11.csv', 'w', newline="") as outfile:
    writer = csv.writer(outfile)

Documentation Links

Leave a Comment