python - Why I output csv file with a blank row -


this code:

with open("testoffset.csv") handler:     f = open('output_file2.csv', 'w+')     f.write('x,y,value\n')     r,l in enumerate(handler):         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 output csv file without blank rows?

your lines handler file have newline @ end, write output file.

remove newline stripping before split line:

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

you may want avoid re-inventing csv reading , writing wheels; python comes excellent csv module can work you, including removing newline , splitting lines:

import csv  open("testoffset.csv", 'rb') handler, open('output_file2.csv', 'wb') output:     reader = csv.reader(handler)     writer = csv.writer(output)     writer.writerow(['x', 'y', 'value'])     rownum, row in enumerate(reader, 1):         colnum, col in enumerate(row, 1):             writer.writerow([rownum, colnum, col]) 

i started enumerate() calls @ 1 avoid having add 1 when writing.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -