错误:尝试从一档案柜中读取字典时,pickle数据被截断。

2024-10-01 13:24:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一名教师,我正在尝试编写一个简单的函数,将学生的电子邮件保存在字典中,以供其他程序使用。我需要在多个执行之间保存字典,所以我尝试使用shelve来保存它;但是,在第二次运行该函数之后,我收到一个不匹配的错误,说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中创建空字典shelfile['studentEmails']。第一次运行会很好,但是当我试图将shelfile分配回studentEmails时,请给出_pickle.UnpicklingError: pickle data was truncated错误。我是新手,还在学习,所以我很感激你的帮助。在


Tags: 函数程序inputif字典emailpickleshelve
2条回答

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

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

我假设你也有同样的错误,也许你通过终止程序或其他什么东西退出了无限while循环?在

在玩弄了一些东西并阅读了一些其他网站之后,我能够用pickle而不是{}来实现我想要的。下面是代码现在的样子:

import pickle
loadData = open('saveData.p','rb')
studentEmails = pickle.load(loadData)
loadData.close()
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()
saveData = open('saveData.p','wb')
pickle.dump(studentEmails,saveData)
saveData.close()

这对我正在做的很好。我不得不用占位符在shell中创建studentEmails字典,因为pickle不允许空字典。在

相关问题 更多 >