Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to CSV with Python adds blank lines [duplicate]

I am trying to write to CSV file but there are blank rows in between. How can I remove the blank rows?

import csv b = open('test.csv', 'w') a = csv.writer(b) data = [['Me', 'You'],\         ['293', '219'],\         ['54', '13']] a.writerows(data) b.close() 
like image 306
user2031063 Avatar asked Feb 04 '13 19:02

user2031063


People also ask

How do I stop repeating header when writing csv?

Create an if condition to check for the need for writing headers. If headers exist no need to write headers. Empty/new CSV = write headers and you can leave out the writing header from that point on. I've gone ahead and added a section that will answer your loop question.

Can csv have empty lines?

I just checked: Python's CSV parser ignores empty lines. I guess that's reasonable. Yes, I agree an empty line within a quoted field means a literal empty line.

How do you overwrite a row in a CSV file in Python?

You cannot overwrite a single row in the CSV file. You'll have to write all the rows you want to a new file and then rename it back to the original file name.


1 Answers

The way you use the csv module changed in Python 3 in several respects (docs), at least with respect to how you need to open the file. Anyway, something like

import csv with open('test.csv', 'w', newline='') as fp:     a = csv.writer(fp, delimiter=',')     data = [['Me', 'You'],             ['293', '219'],             ['54', '13']]     a.writerows(data) 

should work.

like image 69
DSM Avatar answered Sep 30 '22 16:09

DSM