簡體   English   中英

Python 3.3轉儲和加載腌制字典

[英]Python 3.3 dump and load pickled dictionary

我正在研究Tony Gaddis的“ Starting Out With Python”第三版中的章節練習,該課程是我之前學習的。 我在第9章中,練習8要求我編寫一個程序,該程序在關閉文件時將字典(名稱: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()

如果使用open("my_file","r")打開文件進行讀取,則不會更改該文件。 該文件必須已經存在。 如果使用open("my_file","w")要寫入的文件,它將創建一個新文件,如果存在則覆蓋舊文件。 第一種形式(讀取)是默認格式,因此您可以根據需要省略第二個"r"參數。 這在Python標准庫文檔中有所記錄。

使用open(“ myfile”,'r +'),這允許讀取和寫入功能。 (至少在2.7中)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM