Writing to CSV with Python adds blank lines [duplicate]
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()
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.
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.
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
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')
.
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')