0

私は、以前に受講したクラスの Tony Gaddis の「Starting Out With Python」第 3 版の章演習に取り組んでいます。私は第 9 章にいますが、演習 8 では、辞書 (name:email) をファイルにピクルするプログラムを作成する必要があります。ファイルを閉じるときにファイルをピクル解除し、開いたときにデータを保持しているファイルをアンピクルします。その章のすべての単語を読みましたが、同じファイルで両方を行う方法をまだ理解していません。open 関数を使用すると、私の理解では、データのない新しいファイルであるファイルが作成されます。ダンプを配置してコード行をロードする場所など、シーケンスの問題である可能性があると考えていますが、それも意味がありません。ロジックは、ダンプする前にファイルを開く必要があることを示しています。

「open」関数がファイル オブジェクトを作成し、それをファイルに関連付け、この関数がコードの早い段階で (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()
4

2 に答える 2