Writing to CSV with Python adds blank lines

user2031063 picture user2031063 · Feb 4, 2013 · Viewed 220.1k times · Source

I am trying to write to CSV file but there are blank rows in between. How can I remove the blank rows?

import csv
b = open('test.csv', 'w')
a = csv.writer(b)
data = [['Me', 'You'],\
        ['293', '219'],\
        ['54', '13']]
a.writerows(data)
b.close()

Answer

DSM picture DSM · Feb 4, 2013

The way you use the csv module changed in Python 3 in several respects (docs), at least with respect to how you need to open the file. Anyway, something like

import csv
with open('test.csv', 'w', newline='') as fp:
    a = csv.writer(fp, delimiter=',')
    data = [['Me', 'You'],
            ['293', '219'],
            ['54', '13']]
    a.writerows(data)

should work.