更新: 我尝试了两个单独的函数来保存和加载字典。工作得很漂亮。但仍有问题。该程序将无法识别电子邮件行= updatedEmails
它会非常好,而且这些内容都在各自的字典中,但是我无法将它们分配给全局“电子邮件”,而所有其他功能都会改变
=============================================== ==
import pickle
dataList = open('data.txt','wb')
global emails
emails = {}
def loading():
inFile = open('data.txt', 'rb')
updatedEmails = pickle.load(inFile)
print (updatedEmails)
inFile.close()
def saving(emails):
dataList = open('data.txt', 'wb')
pickle.dump(emails, dataList)
dataList.close()
def displayMenu():
print('\t\t\t\tMenu')
print('\t5)Display the list')
print('\t6)Quit')
def main():
choice = 0
loading()
while choice != 6:
displayMenu()
choice = int(input('Enter your choice: '))
if choice == 1:
add()
elif choice == 6:
saving(emails)
elif choice == 7:
loading()
emails = updatedEmails
main()
答案 0 :(得分:2)
您的代码打开了用于编写的
的pickle文件。dataList = open('data.txt','wb')
将文件截断为0;当你尝试从同一个文件加载泡菜时它是空的。
只有当你真正要为它写一个新的泡菜时才打开文件进行书写,而不是之前。