UnpicklingError: pickle data was truncated when trying to read a dictionary from a shelved file

J. Browning picture J. Browning · Nov 7, 2017 · Viewed 10.5k times · Source

I'm a teacher, and I'm trying to write a simple function that saves my students' emails in a dictionary for use in another program. I need the dictionary to be saved across multiple executions, so I'm trying to use shelve to save it; however, after running the function for a second time, I get an unpickling error saying the pickle data was truncated. Here is the code:

shelfFile = shelve.open('mydata')
studentEmails = shelfFile['studentEmails']
def inputEmails():
    while True:
        nameInput = input('Name: ')
        if nameInput == '':
            break
        emailInput = input('Email: ')
        if emailInput == '':
            print('Email not entered. Please try again.')
            continue
        while True:
            print('Is this information correct? [Y]es or [N]o')
            print('Name: ' + nameInput)
            print('Email: ' + emailInput)
            correctChoice = input('[Y] or [N]: ').upper()
            if correctChoice == 'Y':
                studentEmails[nameInput] = emailInput
                break
            elif correctChoice == 'N':
                print('Okay. Please input again.')
                break
            else:
                print('I did not understand that response.')
inputEmails()
shelfFile['studentEmails']=studentEmails
shelfFile.close()

I create the empty dictionary shelfFile['studentEmails'] in the shell before I run the program. It will run fine the first time, but give me the _pickle.UnpicklingError: pickle data was truncated error when I try to assign the shelfFile back to studentEmails. I'm new at this and still learning, so I appreciate the help.

Answer

HUCK45 picture HUCK45 · Jun 16, 2018

I just had the same problem, and after a little investigation I realized it probably happened because I stopped my program like a jerk (terminated it in the middle of using the shelve).

So I deleted my shelve and created it again and everything worked fine.

I assume you had the same error, maybe you exited your infinite while loops by terminating the program or something?