[Tutor] How do I fix this StopIteration error?

Kent Johnson kent37 at tds.net
Fri Dec 16 12:04:28 CET 2005

Nathan Pinno wrote:
>>        store = open(filename,'r')
>        for line in store:
>           conv = line.strip()
>           rate = float(store.next().strip())
>           exch[conv] = rate
> When I ran the program, I got this:
> Traceback (most recent call last):
>   File "D:\Python24\exchange.py", line 45, in -toplevel-
>     load_rates(rates)
>   File "D:\Python24\exchange.py", line 19, in load_rates
>     rate = float(store.next().strip())
> StopIteration
> How do I fix this?

StopIteration is an iterator's way of saying it has reached the end. When you iterate 
using a for loop, the exception is caught internally and used to terminate the loop. When 
you call next() explicitly, you should be prepared to catch the exception yourself.

In this case though, the exception means you have a conv without a rate, so it is a 
symptom of bad data or an error reading the data.

Have you looked at the file to make sure it is correct? If it is, you might try a slightly 
different loop. I'm not sure if it really works to mix a for loop iteration with calls to 
next() on the iterator. Try something like this:

    store = open(filename,'r')
        while True:
           conv = store.next().strip()
           rate = float(store.next().strip())
           exch[conv] = rate
    except StopIteration:

Or use the pickle module to save and load your exch dictionary, it is perfect for this and 
as simple as

import pickle
# save
store = open(filename, 'wb')
pickle.dump(exch, store)

# load
store = open(filename, 'b')
exch = pickle.load(store)


More information about the Tutor mailing list