I am trying to write a couple of tuples to a csv file.
This is what I tried:
out_file = open('csv_write.csv', 'w')
writer = csv.writer(out_file)
writer.writerow((0, 1, 2))
writer.writerow((3, 4, 5))
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
...it must be opened with the ‘b’ flag on platforms where that makes a difference.
...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
\r\n, resulting in
\r\r\n. This causes your extra blank rows.