简体   繁体   中英

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM