Ian Chang
Ian Chang

Reputation: 7

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+')
    f.write('X,Y,value\n')
    for r,l in enumerate(handler):
        for col, e in enumerate(l.split(',')):
            f.write('{0},{1},{2}\n'.format(r+1,col+1,e))

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?

Upvotes: 0

Views: 64

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

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.

Upvotes: 2

alec_djinn
alec_djinn

Reputation: 10789

Just skip empty lines.

...
for r,l in enumerate(handler):
    if not l.startswith('\n'): #or if l[0] != '\n':
        for col, e in enumerate(l.split(',')):
            ...

Upvotes: 1

Sayali Sonawane
Sayali Sonawane

Reputation: 12599

with open("testoffset.csv",'wb') as handler:

Replace first line of your code.

Upvotes: 0

Related Questions