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:
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With