Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write tuples in a csv file in python with no blank line

Tags:

python

csv

I am trying to write a couple of tuples to a csv file.

This is what I tried:

import csv
out_file = open('csv_write.csv', 'w')
writer = csv.writer(out_file)
writer.writerow((0, 1, 2))
writer.writerow((3, 4, 5))
out_file.close()

This worked, but not as expected. Notice the blank rows in a spreadsheet:

screenshot of spreadsheet rows showing unwanted blank lines

and in a text editor, the file looks like:

0,1,2
<blank line>
3,4,5
<blank line>

(total 4 rows)

How can I write without these blank rows?

like image 405
hola Avatar asked Aug 20 '13 06:08

hola


1 Answers

The csv module does its own end-of-line handling, and requires the output file to be opened in a specific way:

out_file = open('csv_write.csv', 'wb')             # Python 2.x
out_file = open('csv_write.csv', 'w', newline='')  # Python 3.x

Reference http://docs.python.org/2.7/library/csv.html?highlight=csv#csv.writer:

...it must be opened with the ‘b’ flag on platforms where that makes a difference.

And http://docs.python.org/3.3/library/csv.html?highlight=csv#csv.writer:

...it should be opened with newline=''...

Your blank lines are due to the default "dialect" of the csv module being excel. That dialect defines lineterminator='\r\n' and those characters are written directly to the stream. Opening the output file in text mode on Python 2 or without newline='' on Python 3 "on platforms where that makes a difference" (Windows) translates all \n in the output stream to \r\n, resulting in \r\r\n. This causes your extra blank rows.

like image 127
Mark Tolonen Avatar answered Sep 29 '22 22:09

Mark Tolonen