+2 votes
in Programming Languages by (73.8k points)

I am using the following code to create a CSV file using Python. The code creates CSV file without any error, but it has a blank line after every data line. How to remove the blank line?

import csv
a1={'CO':[23,12], 'FL':[43,54]}
a2={'CO':[3223,3231], 'FL':[4343,5654]}
flds = ['state','2003','p1','2004','p2']
rec_dict = {}
with open('mytest.csv', 'w') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=flds)
    writer.writeheader()
    for k,v in a1.items():
        j=0
        rec_dict['state'] = k
        rec_dict['2003'] = v[0]
        rec_dict['p1'] = v[0]*1.0/a2[k][0]
        rec_dict['2004'] = v[1]
        rec_dict['p2'] = v[1]*1.0/a2[k][1]
        writer.writerow(rec_dict)

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

If you are using Python2, you need to open your output CSV file in 'wb' mode instead of 'w' mode. It worked for me and hopefully will solve your problem too. Use the following line.

with open('mytest.csv', 'wb') as csvfile:

If you are using Python3,  'w' mode should not put the blank line.


...