CSV file written with Python has blank lines between each row

The csv.writer module directly controls line endings and writes \r\n into the file directly. In Python 3 the file must be opened in untranslated text mode with the parameters 'w', newline="" (empty string) or it will write \r\r\n on Windows, where the default text mode will translate each \n into \r\n.

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

In Python 2, use binary mode to open outfile with mode 'wb' instead of 'w' to prevent Windows newline translation. Python 2 also has problems with Unicode and requires other workarounds to write non-ASCII text. See the Python 2 link below and the UnicodeReader and UnicodeWriter examples at the end of the page if you have to deal with writing Unicode strings to CSVs on Python 2, or look into the 3rd party unicodecsv module:

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

Documentation Links

  • https://docs.python.org/3/library/csv.html#csv.writer
  • https://docs.python.org/2/library/csv.html#csv.writer

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)