Python 3.3转储和加载pickled字典

时间:2016-03-15 01:33:57

标签: python dictionary serialization python-3.3 jsonpickle

我正在完成Tony Gaddis的章节练习"从Python开始#34;我之前参加过的第3版。我在第9章和练习8中要求我编写一个程序,在程序关闭时将字典(名称:电子邮件)发送到文件,并在打开时取消保留数据的文件。我已阅读该章中的每一个字,我仍然不明白你如何在同一个文件中做到这两个方面。当您使用open函数时,它会创建一个文件,据我所知,该文件是一个没有数据的新文件。我认为它可能是一个排序问题,比如在哪里放置转储和加载代码行,但这也没有意义。逻辑规定你必须先打开文件才能转储它。

如果打开' function创建一个文件对象并将其与一个文件相关联,这个函数出现在代码的早期(如def main中),是什么阻止它在每次调用该行时将文件归零?

这不是家庭作业。我完成了那门课。我这样做是为了我自己的启发,并希望任何有助于我理解它的解释。我已经将我的尝试包括在下面的代码中反映出来的解决方案中,并且会一直啃着它直到找到解决方案。我只是想,因为基因库在这里更深,我会节省一些时间和挫折。非常感谢那些选择回复的人,如果我缺少任何有助于澄清这个问题的相关数据,请告诉我。

import pickle

#global constants for menu choices
ADDNEW = 1
LOOKUP = 2
CHANGE = 3
DELETE = 4
EXIT = 5

#create the main function
def main():

    #open the previously saved file
    friends_file = open('friends1.txt', 'rb')
    #friends = pickle.load(friends_file)
    end_of_file = False
    while not end_of_file:
        try:
            friends = pickle.load(friends_file)
            print(friends[name])
        except EOFError:
            end_of_file = True
        friends_file.close()

    #initialize variable for user's choice
    choice = 0

    while choice != EXIT:
        choice = get_menu_choice() #get user's menu choice

        #process the choice
        if choice == LOOKUP:
            lookup(friends)
        elif choice == ADDNEW:
            add(friends)
        elif choice == CHANGE:
            change(friends)
        elif choice == DELETE:
            delete(friends)

#menu choice function displays the menu and gets a validated choice from the user
def get_menu_choice():
    print()
    print('Friends and Their Email Addresses')
    print('---------------------------------')

    print('1. Add a new email')
    print('2. Look up an email')
    print('3. Change a email')
    print('4. Delete a email')
    print('5. Exit the program')
    print()

    #get the user's choice
    choice = int(input('Enter your choice: '))

    #validate the choice
    while choice < ADDNEW or choice > EXIT:
        choice = int(input('Enter a valid choice: '))
    #return the user's choice
    return choice

#the add function adds a new entry into the dictionary
def add(friends):

    #open a file to write to
    friends_file = open('friends1.txt', 'wb')

    #loop to add data to dictionary
    again = 'y'    
    while again.lower() == 'y':

        #get a name and email
        name = input('Enter a name: ')
        email = input('Enter the email address: ')

        #if the name does not exist add it
        if name not in friends:
            friends[name] = email
        else:
            print('That entry already exists')
            print()

        #add more names and emails
        again = input('Enter another person? (y/n): ')

    #save dictionary to a binary file
    pickle.dump(friends, friends1.txt)
    friends1.close()

#lookup function looks up a name in the dictionary
def lookup(friends):

    #get a name to look up
    name = input('Enter a name: ')

    #look it up in the dictionary
    print(friends.get(name, 'That name was not found.'))

#the change function changes an existing entry in the dictionary
def change(friends):
    #get a name to look up
    name = input('Enter a name: ')

    if name in friends:
        #get a new email
        email = input('Enter the new email address: ')

        #update the entry
        friends[name] = email
    else:
        print('That name is not found.')

#delete an entry from the dictionary
def delete(friends):
    #get a name to look up
    name = input('Enter a name: ')
    #if the name is found delete the entry
    if name in friends:
        del [name]
    else:
        print('That name is not found.')

#call the main function
main()

2 个答案:

答案 0 :(得分:0)

如果您使用open("my_file","r")打开文件进行阅读,则不会更改该文件。该文件必须已存在。如果您使用open("my_file","w")打开要写入的文件,它将创建一个新文件,如果存在则覆盖旧文件。第一个表单(读取)是默认值,因此如果需要,可以省略第二个"r"参数。这在Python标准库文档中有记录。

答案 1 :(得分:0)

使用open(&#34; myfile&#34;,&#39; r +&#39;)这允许读写功能。 (至少在2.7中)