jensph
jensph

Reputation: 785

How to handle exceptions when reading rows of a file?

Is there a way to handle exceptions when reading a specific row of a file?

For example, say I have this block:

with open(fileIn, 'rb') as f:
    reader = csv.reader(f, delimiter='\t')
    for i, row in enumerate(reader):
        try:
            # stuff
        except:
            pass

and, after parsing half the file, I get the error

IOError: [Errno 22] Invalid argument

on the line

     for i, row in enumerate(reader):

and I'd like to continue parsing the file, skipping the problem row.

Upvotes: 1

Views: 3145

Answers (2)

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19154

for...reader repeatedly calls next(reader). To intercept an exception when looping, do the looping and make the next calls yourself. Untested:

with open(fileIn, 'rb') as f:
    reader = csv.reader(f, delimiter='\t')
    i = -1
    while True:
        i += 1
        try:
            row = next(reader)
        except StopIteration:
            break
        except IOError:
            pass
        else:
            try:
                # stuff
            except:
                pass

Upvotes: 4

Bill Bell
Bill Bell

Reputation: 21643

csv.reader returns an object that both iterates through a file-like iterator and processes what it finds as it reads. You have an IOError which would appear to be irrecoverable. (Am I right about that?) That being the case, wouldn't the best thing you could do be to identify the flaw in the input? Pedro Ghilardi has a suggestion for doing that at reading csv file without for.

Upvotes: 1

Related Questions