kitch6041
kitch6041

Reputation: 113

How to skip the row in a .csv file that causes a ValueError when iterating in Python

In my program I iterate over the rows of a .csv file and perform an operation on each one. In some cases the program is terminated by a ValueError. When this occurs I would like to print an error message and then move onto the next line, rather than having the program stop. Here is the code that iterates over the file:

with open(filename, 'rb') as f:
    reader = csv.reader(f, dialect=csv.excel_tab)
for row in reader:
        strrow = str(row)
        getInfo(strrow)

Upvotes: 0

Views: 2636

Answers (3)

jonrsharpe
jonrsharpe

Reputation: 122032

The other answers are correct to identify try: except: as the code to use here, but have applied it incorrectly. To avoid catching errors you actually need to hear about (and, in this case, to let you actually keep iterating over the reader), only the line whose errors you explicitly want to handle needs to be wrapped in a try. As there's not much that can't be made a string, I'd guess that means:

with open(filename, 'rb') as f:
    reader = csv.reader(f, dialect=csv.excel_tab)
for row in reader:
        strrow = str(row)
        try:
            getInfo(strrow)
        except ValueError:
            print("Couldn't process line: {0}".format(strrow))

However, this does bring up a few questions:

  1. Why not pass the actual list to getInfo? It seems pointless to use csv to parse the file from strings to lists, then turn the lists back into strings, when you could actually pass the list (and probably save some parsing).
  2. Why not put the error handling inside getInfo? Within that function you know exactly what is going wrong with which part of the line (and can therefore provide a much more helpful message to the user); outside, all you know is that something went wrong.

If you made both those changes, the code here would be much simpler:

with open(filename, 'rb') as f:
    reader = csv.reader(f, dialect=csv.excel_tab)
map(getInfo, reader)

Upvotes: 1

jcklie
jcklie

Reputation: 4094

What you want is using a try-catch block. What it basically does is executing the code in the try-block, and when an exception occurs (and there is a matching catch-block), it executes the block.

with open(filename, 'rb') as f:
    reader = csv.reader(f, dialect=csv.excel_tab)
    try:
        for row in reader:
            strrow = str(row)
            getInfo(strrow)
    except ValueError:
        print "Oops!  That was no valid row..."

Source: Python Doc

Upvotes: 1

user3364120
user3364120

Reputation: 23

I'd think this is the typical use case for a try-except block:

with open(filename, 'rb') as f:
    reader = csv.reader(f, dialect=csv.excel_tab)
    for row in reader:
        try:
            strrow = str(row)
            getInfo(strrow)
        except ValueError:
            print('Error!')

Upvotes: 1

Related Questions