duckman
duckman

Reputation: 747

skip an error row in a for loop

I am iterating through each row in a csv file and choose/calculate only rows that meet the condition. However, when there is an error in a row, it stops the loop. is there a way to tell python to skip the error and move to the next row? I use the try function but did not work. my code is

try(row['BAS'] = float(row['Close Ask']) - float(row['Close Bid']))

the error is one of the cell is a string and cannot be converted into a float

Upvotes: 1

Views: 8985

Answers (3)

lint
lint

Reputation: 98

you should put your code inside a try/except:

try:
    code
except:
    pass

(you shouldn't use such broad exception catching but I don't know the error that is occuring.)

Upvotes: -1

donkopotamus
donkopotamus

Reputation: 23186

You want something like:

for row in csv_file:
    try: 
        x = float(row['Close Ask']) - float(row['Close Bid'])
    except ValueError:
        continue
    else:
        # now keep going doing something with x
        ...

Upvotes: 3

101
101

Reputation: 8999

You can ignore the error by catching errors of that type (ValueError) and effectively ignoring it:

try:
    row['BAS'] = float(row['Close Ask']) - float(row['Close Bid'])
except ValueError:
    pass

Upvotes: -1

Related Questions