Aamash Haroon
Aamash Haroon

Reputation: 67

Python: Return a blank and continue for loop after exception

I have a for loop where I'm using an API key to return some values into a CSV. I want the loop to return a blank row every time there's an error rather than the code breaking. I know I need to use a continue but not sure how to insert a blank row for every indexError I get.

I've written a function called get_data that returns the response text from the API. So using that, this is what I'm trying to run for an input file df

d = []
try: 
    for i in range(len(df)):
        output = df.loc[i,"column_1"] 
        d.append(get_data(output))
        lat = pd.DataFrame(d)
        lat_lon= lat.apply(pd.Series)
        f = open('results.csv','w')
        lat_lon.to_csv('results.csv')
except IndexError: 
        print('ERROR at index {}: {!r}'.format(i, address))

I want the output csv file results.csv to leave a blank row every time there was an indexError

Upvotes: 0

Views: 843

Answers (1)

Barmar
Barmar

Reputation: 781068

try/except needs to be inside the loop. Otherwise you abort the entire loop when the exception occurs.

Also, you shouldn't write the CSV file every time through the loop. Write it at the end with the complete contents of d.

d = []
for i in range(len(df)):
    try: 
        output = df.loc[i,"column_1"] 
        d.append(get_data(output))
    except IndexError: 
        print('ERROR at index {}: {!r}'.format(i, address))
        d.append([default row goes here])
lat = pd.DataFrame(d)
lat_lon= lat.apply(pd.Series)
f = open('results.csv','w')
lat_lon.to_csv('results.csv')

Upvotes: 1

Related Questions