Delete blank rows from CSV?

Use the csv module:

import csv
...

with open(in_fnam, newline="") as in_file:
    with open(out_fnam, 'w', newline="") as out_file:
        writer = csv.writer(out_file)
        for row in csv.reader(in_file):
            if row:
                writer.writerow(row)

If you also need to remove rows where all of the fields are empty, change the if row: line to:

if any(row):

And if you also want to treat fields that consist of only whitespace as empty you can replace it with:

if any(field.strip() for field in row):

Note that in Python 2.x and earlier, the csv module expected binary files, and so you’d need to open your files with e 'b' flag. In 3.x, doing this will result in an error.

Leave a Comment