UnpicklingError:尝试从搁置文件中读取字典时,pickle 数据被截断

J. *_*ing 6 python dictionary shelve pickle

我是一名老师,我正在尝试编写一个简单的函数,将学生的电子邮件保存在字典中,以便在另一个程序中使用。我需要在多次执行中保存字典,因此我尝试使用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()
Run Code Online (Sandbox Code Playgroud)

在运行程序之前,我在 shell 中创建了空字典 shelfFile['studentEmails'] 。第一次它会运行良好,但当_pickle.UnpicklingError: pickle data was truncated我尝试将shelfFile分配回studentEmails时,会出现错误。我对此很陌生,仍在学习,所以我很感谢您的帮助。

J. *_*ing 0

在尝试了一些事情并阅读了其他一些网站之后,我能够使用pickle而不是实现我想要的目标shelve。代码现在如下所示:

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()
Run Code Online (Sandbox Code Playgroud)

这对于我正在做的事情来说效果很好。我必须在 shell 中使用占位符创建 StudentEmails 字典,因为pickle不允许使用空字典。