Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python CSV delete empty rows [duplicate]

Im having a hard time trying to delete empty(blank) rows from a csv file using python 3.4.3. Each time I run my script the output remains the same as the original.

  import csv
  ...


 with open('demo004.csv') as input, open('demo005.csv', 'w') as output:
      writer = csv.writer(output)
      for row in csv.reader(input):
          if any(field.strip() for field in row):
             writer.writerow(row)
      input.close()
      output.close()

My CSV file is in the format.

AA,AB,AC

BA,BB,BC

CA,CB,CB

Whereas I would like to obtain

AA,AB,AC
BA,BB,BC
CA,CB,CB
like image 587
Michal K Avatar asked Jan 29 '26 12:01

Michal K


2 Answers

When you are trying to open the file which you want to write to, open it with an additional parameter, newline=''

import csv
  ...


 with open('demo004.csv') as input, open('demo005.csv', 'w', newline='') as output:
     writer = csv.writer(output)
     for row in csv.reader(input):
         if any(field.strip() for field in row):
             writer.writerow(row)
like image 91
Kapil Marwaha Avatar answered Feb 01 '26 00:02

Kapil Marwaha


If you're only interested in removing blank lines (ie, ones that are empty or perhaps contain only whitespace), then you don't need to worry about the fact that the other lines are CSV. That means you can just do:

with open('demo004.csv') as input, open('demo005.csv', 'w') as output:
    non_blank = (line for line in input if line.strip())
    output.writelines(non_blank)
like image 40
lvc Avatar answered Feb 01 '26 02:02

lvc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!