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
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With