2

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
Michal K
  • 245
  • 2
  • 9
  • 17
  • What is the delimiter in your original files? I'm guessing commas since you do not specify? If you could link some of the data in `demo004.csv` or `demo005.csv` that would be helpful – asdf Aug 22 '15 at 22:02
  • 2
    Please include a complete example in your posting, particularly a short data set for input, the output, and the desired output. The file names shown won't let helpers duplicate the problem. – Paul Aug 22 '15 at 22:03
  • 2
    Is that the real code? Closing the input/output at that indentation level (which is unnecessary anyway giving the use of `with` statement) would be causing exceptions – Jon Clements Aug 22 '15 at 22:04
  • Please provide enough code and sample data to replicate the problem. – martineau Aug 22 '15 at 22:06
  • I using a "," as delimiter. I used the with statement because of the version of python according to what I read, – Michal K Aug 22 '15 at 22:07
  • That gives me an invalid syntax at "as". – Michal K Aug 22 '15 at 22:44
  • Here is a screen shot http://tinypic.com/view.php?pic=fvw7d4&s=8#.Vdj_fZdmo9s – Michal K Aug 22 '15 at 23:03
  • 1
    @MichalK: your screenshot shows both that you removed the `with`, and it looks like you removed the colon you need at the end of the line. Start with your original code (which works for me) and simply add `newline=''` inside both opens. – DSM Aug 22 '15 at 23:05
  • That worked, kindly explain how the newline came into play. Thanks – Michal K Aug 22 '15 at 23:20

2 Answers2

8

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)
Kapil Marwaha
  • 949
  • 9
  • 9
1

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)
lvc
  • 34,233
  • 10
  • 73
  • 98