pushpen.paul pushpen.paul - 1 month ago 7
Python Question

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

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?

Answer

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. This translates linefeed \n characters into carriage return/linefeed \r\n, but opening the output file in text mode "on platforms where that makes a difference" (Windows) also translates \n to \r\n, resulting in \r\r\n. This causes your extra blank rows.

Comments