【发布时间】:2017-11-07 15:39:11
【问题描述】:
我是一名教师,我正在尝试编写一个简单的函数,将学生的电子邮件保存在字典中,以便在另一个程序中使用。我需要在多次执行中保存字典,所以我尝试使用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错误。我是这方面的新手,还在学习,所以非常感谢您的帮助。
【问题讨论】:
标签: python dictionary pickle shelve