[英]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.