Writing to CSV with Python adds blank lines

PythonCsvPython 3.3

Python Problem Overview


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()

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

If you're using Python 2.x on Windows you need to change your line open('test.csv', 'w') to open('test.csv', 'wb'). That is you should open the file as a binary file.

However, as stated by others, the file interface has changed in Python 3.x.

Solution 3 - Python

import csv

hello = [['Me','You'],['293', '219'],['13','15']]
length = len(hello[0])

with open('test1.csv', 'wb') as testfile:
    csv_writer = csv.writer(testfile)
    for y in range(length):
        csv_writer.writerow([x[y] for x in hello])

will produce an output like this

Me You
293 219
13 15

Hope this helps

Solution 4 - Python

You need to open the file in binary b mode to take care of blank lines in Python 2. This isn't required in Python 3.

So, change open('test.csv', 'w') to open('test.csv', 'wb').

Solution 5 - Python

Pyexcel works great with both Python2 and Python3 without troubles.

Fast installation with pip:

pip install pyexcel

After that, only 3 lines of code and the job is done:

import pyexcel
data = [['Me', 'You'], ['293', '219'], ['54', '13']]
pyexcel.save_as(array = data, dest_file_name = 'csv_file_name.csv')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2031063View Question on Stackoverflow
Solution 1 - PythonDSMView Answer on Stackoverflow
Solution 2 - PythonWilduckView Answer on Stackoverflow
Solution 3 - PythonJohn SmithView Answer on Stackoverflow
Solution 4 - PythonAdityaView Answer on Stackoverflow
Solution 5 - PythonDanny LessioView Answer on Stackoverflow