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()
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With