Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

csv, dictionary, python

Solution

By default, the classes in the `csv` module use Windows-style line terminators (`\r\n`) rather than Unix-style (`\n`). Could this be what’s causing the apparent double line breaks?

If so, in python 2 you can override it in the `DictWriter` constructor:

output = csv.DictWriter(open('file3.csv','w'), delimiter=',', lineterminator='\n', fieldnames=headers)

Problem

I am using DictWriter to output data in a dictionary to a csv file. Why does the CSV file have a blank line in between each data line? It's not a huge deal, but my dataset is big and doesn't fit into one csv file because it has too many lines since the "double-spacing" doubles the number of lines in the file. My code for writing to the dictionary is: ``` headers=['id', 'year', 'activity', 'lineitem', 'datum'] output = csv.DictWriter(open('file3.csv','w'), delimiter=',', fieldnames=headers) output.writerow(dict((fn,fn) for fn in headers)) for row in rows: output.writerow(row) ```

Original source

Related problems