Skip to main content
 首页 » 编程设计

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

2025年01月19日11Free-Thinker

我是一名教师,我正在尝试编写一个简单的函数,将我学生的电子邮件保存在字典中,以便在另一个程序中使用。我需要在多次执行中保存字典,所以我尝试使用 shelve 来保存它;然而,在第二次运行该函数后,我收到一个 unpickling 错误,指出 pickle 数据被截断了。这是代码:

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() 

在运行程序之前,我在 shell 中创建了空字典 shelfFile['studentEmails']。它第一次运行良好,但是当我尝试将 shelfFile 分配回 studentEmails 时给我 _pickle.UnpicklingError: pickle data was truncated 错误。我是新手,仍在学习中,因此非常感谢您的帮助。

请您参考如下方法:

我只是遇到了同样的问题,经过一些调查我意识到这可能是因为我像个 SCSS 一样停止了我的程序(在使用搁置的过程中终止了它)。

所以我删除了我的货架并重新创建了它,一切正常。

我假设你有同样的错误,也许你通过终止程序或其他方式退出了你的无限循环?