Search code examples
pythoncsvpython-3.xblank-line

python csv reader ignore blank row


Im using the pythons csv reader . How can I use the following code in such a way that it ignores blank lines.

import csv
f1 = open ("ted.csv")
oldFile1 = csv.reader(f1, delimiter=',', quotechar='"')
oldList1 = list(oldFile1)
f2 = open ("ted2.csv")
newFile2 = csv.reader(f2, delimiter=',', quotechar='"')
newList2 = list(newFile2)

f1.close()
f2.close()

with open("ted.csv") as f1, open("ted2.csv") as f2, open('foo.csv', 'w') as out:
     r1, r2 = csv.reader(f1), csv.reader(f2)
     st = set((row[0], row[3]) for row in r1)
     wr = csv.writer(out)
     for row in (row for row in r2 if (row[0],row[3]) not in st):
           wr.writerow(row)

Solution

  • If your csv files start with a blank line, I think you should be able to skip that line with readline() before creating the csv reader:

    with open("ted.csv") as f1, open("ted2.csv") as f2, open('foo.csv', 'w') as out:
        f1.readline()
        f2.readline()
        r1, r2 = csv.reader(f1), csv.reader(f2)