Ian Chang Ian Chang - 2 months ago 13
Python Question

Why I output csv file with a blank row

This is my code:

with open("testoffset.csv") as handler:
f = open('output_file2.csv', 'w+')
for r,l in enumerate(handler):
for col, e in enumerate(l.split(',')):

This outputs

X Y value
1 1 1
1 2 2
1 3 3
blank row
2 1 2
2 2 2
2 3 2
blank row
3 1 1
3 2 2
3 3 3
blank row

How can I output a CSV file without those blank rows?


Your lines from the handler file have a newline at the end, which you write to your output file.

Remove that newline by stripping before you split the line:

for col, e in enumerate(l.rstrip('\n').split(',')):

You may want to avoid re-inventing the CSV reading and writing wheels; Python comes with the excellent csv module that can do all this work for you, including removing the newline and splitting the lines:

import csv

with open("testoffset.csv", 'rb') as handler, open('output_file2.csv', 'wb') as output:
    reader = csv.reader(handler)
    writer = csv.writer(output)
    writer.writerow(['X', 'Y', 'value'])
    for rownum, row in enumerate(reader, 1):
        for colnum, col in enumerate(row, 1):
            writer.writerow([rownum, colnum, col])

I also started the enumerate() calls at 1 to avoid having to add one when writing.