Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty space in between rows after using writer in python

I am using csv package now, and every time when I write to a new csv file and open it with excel I will find a empty row in between every two rows.

filereader = csv.reader(open("tests.csv", "r"), delimiter=",")
filewriter = csv.writer(open("test_step1.csv", "w"), delimiter=",")
#Delete header
for row in filereader:
    if row[0].isdigit():
        filewriter.writerow(row)

enter image description here

like image 972
user1998777 Avatar asked May 31 '13 19:05

user1998777


People also ask

Why CSV writer adds blank rows?

The way Python handles newlines on Windows can result in blank lines appearing between rows when using csv. writer . In Python 2, opening the file in binary mode disables universal newlines and the data is written properly.

Which of the following parameters should be added with open function to avoid blank row followed file Each row in CSV?

In a with-as-statement, use open(file, mode, newline=None) with mode as "w" to open a stream of a . csv file file for writing. Set newline to "" to prevent blank rows when writing.


1 Answers

You need to open the file in wb mode try:

import csv

filereader = csv.reader(open("tests.csv", "r"), delimiter=",")
filewriter = csv.writer(open("test_step1.csv", "wb"), delimiter=",", newline="")
#Delete header
for row in filereader:
    if row[0].isdigit():
        filewriter.writerow(row)

The csv.writer writes \r\n into the file directly.

If you don't open the file in binary mode, it will write \r\r\n because on Windows text mode will translate each \n into \r\n.

edit:

For python 3 had to add newline="" to csv.writer as per this answer

like image 56
Noelkd Avatar answered Oct 12 '22 13:10

Noelkd