0

更新:我尝试制作两个单独的函数来保存和加载字典。工作精美。但是还有一个问题。该程序将无法识别行 emails = 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()
4

1 回答 1

2

您的代码首先打开了 pickle 文件进行编写:

dataList = open('data.txt','wb')

这会将文件截断为 0;当您尝试从同一个文件加载泡菜时,它是空的。

仅当您实际要向其写入新的泡菜时才打开文件进行写入,而不是之前。

于 2014-05-02T12:34:16.323 回答