Blank row getting inserted between each row of excel while using CSV writer in Python

I have recently started working on phyton and I just love it. And now I wonder why I didn’t get an opportunity to start earlier.

So here it is. I was trying to write a CSV file. Below is the sample code for the same.

import csv

with open(’emissions.csv’, ‘w’, encoding=”utf-32″) as csvfile:
     filewriter = csv.writer(csvfile, delimiter=’\t’,
                             quotechar=’\u01C0′, quoting=csv.QUOTE_MINIMAL)
     filewriter.writerow([”, ‘Natural Gas’, ‘Diesel’, ‘Fuel oil’, ‘Coke’])
     filewriter.writerow([‘NHV (MJ/Kg)’, ‘51.2’, ’42’, ’40’, ‘30.0’])
     filewriter.writerow([‘\u03B2’, ‘0.76’, ‘0.87’, ‘0.85’, ‘0.74’])
     filewriter.writerow([‘\u03D5’, ‘3.5’, ‘3.7’, ‘3.7’, ‘5.3’])
     filewriter.writerow([‘CER’, ‘0.052’, ‘0.077’, ‘0.079’, ‘0.131’])
     filewriter.writerow([‘COST($/KG)’, ‘0.34’, ‘0.33’, ‘0.28’, ‘0.04’])
   

While everything was working just fine, the emissions.csv file was having a blank row between each record.

image

The problem is, when I am opening the .csv file, I am opening it using ‘w’ option which basically means I am opening it in text mode. Hence “\r\n” is getting printed after each row. Ideally i should always open the .csv file in binary mode using ‘wb’ option.

But in case you are opening it with ‘w’, use the newline=’’ in your open construct

import csv

with open(’emissions.csv’, ‘w’, encoding=”utf-32″, newline=”) as csvfile:
     filewriter = csv.writer(csvfile, delimiter=’\t’,
                             quotechar=’\u01C0′, quoting=csv.QUOTE_MINIMAL)
     filewriter.writerow([”, ‘Natural Gas’, ‘Diesel’, ‘Fuel oil’, ‘Coke’])
     filewriter.writerow([‘NHV (MJ/Kg)’, ‘51.2’, ’42’, ’40’, ‘30.0’])
     filewriter.writerow([‘\u03B2’, ‘0.76’, ‘0.87’, ‘0.85’, ‘0.74’])
     filewriter.writerow([‘\u03D5’, ‘3.5’, ‘3.7’, ‘3.7’, ‘5.3’])
     filewriter.writerow([‘CER’, ‘0.052’, ‘0.077’, ‘0.079’, ‘0.131’])
     filewriter.writerow([‘COST($/KG)’, ‘0.34’, ‘0.33’, ‘0.28’, ‘0.04’])

    

Once you do this, you shall see your .csv file being created without the blank rows.

Hope this helps!

Debajit Dutta

(Microsoft MVP & MCT)