python - Delete blank rows from CSV? -
i have large csv file in rows entirely blank. how use python delete blank rows csv?
after suggestions, have far
import csv # open input csv reading inputcsv = open(r'c:\input.csv', 'rb') # create output csv writing outputcsv = open(r'c:\output.csv', 'wb') # prepare output csv appending appendcsv = open(r'c:\output.csv', 'ab') # create reader object cr = csv.reader(inputcsv, dialect = 'excel') # create writer object cw = csv.writer(outputcsv, dialect = 'excel') # create writer object append ca = csv.writer(appendcsv, dialect = 'excel') # add pre-defined fields cw.writerow(['field1_','field2_','field3_','field4_']) # delete existing field names in input csv # ??????????????????????????? # loop through input csv, check blanks, , write changes append csv row in cr: if row or any(row) or any(field.strip() field in row): ca.writerow(row) # close files inputcsv.close() outputcsv.close() appendcsv.close()
is ok or there better way this?
use csv
module:
import csv ... input = open(in_fnam, 'rb') output = open(out_fnam, 'wb') writer = csv.writer(output) row in csv.reader(input): if row: writer.writerow(row) input.close() output.close()
if need remove rows of fields empty, change if row:
line to:
if any(row):
and if want treat fields consist of whitespace empty can replace with:
if any(field.strip() field in row):
Comments
Post a Comment