[Tutor] How do I fix this IndexError?

Nathan Pinno falcon3166 at hotmail.com
Fri Dec 16 23:37:21 CET 2005

Kent and all,

Here is the latest code:
import pickle
rates = {'can_us' : 0.80276,
         'us_can' : 1.245702,
         'can_euro' : 1.488707,
         'euro_can' : 0.671724}

def save_rates(exch):
    store = open("exch.txt",'w')

def load_rates(exch):
    store = open('exch.txt','r')
    exch = pickle.load(store)

And here is the latest error:
The Currency Exchange Program
By Nathan Pinno

Traceback (most recent call last):
  File "D:\Python24\exchange.py", line 36, in -toplevel-
  File "D:\Python24\exchange.py", line 13, in load_rates
    exch = pickle.load(store)
  File "D:\Python24\lib\pickle.py", line 1390, in load
    return Unpickler(file).load()
  File "D:\Python24\lib\pickle.py", line 872, in load
  File "D:\Python24\lib\pickle.py", line 1207, in load_appends
    mark = self.marker()
  File "D:\Python24\lib\pickle.py", line 888, in marker
    while stack[k] is not mark: k = k-1
IndexError: list index out of range

How do I fix this error?

Thanks for all the help so far,
Nathan Pinno,

MSN Messenger: falcon3166 at hotmail.com
Yahoo! Messenger: spam_swatter31
AIM: f3mighty
ICQ: 199020705  

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