在我的簡介comp sci課程的最後幾天,我們開始創建字典。我們書中的作業程序要求我們創建一些可以查找,添加,更改和刪除一組名稱和電子郵件地址的東西。它要求我們醃製字典,但對我而言,它規定每次程序啓動時,它應該從文件中檢索字典並取消它。我不知道我是否將自己編入了一個角落,但我無法弄清楚如何用我迄今所做的工作來完成此任務。使用Python的pickle打開並保存字典
我的代碼:
import mMyUtils
import pickle
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5
def main():
emails = {}
choice = 0
while choice != QUIT:
choice = getMenuChoice()
if choice == LOOK_UP:
lookUp(emails)
elif choice == ADD:
add(emails)
elif choice == CHANGE:
change(emails)
elif choice == DELETE:
delete(emails)
else:
exit
def getMenuChoice():
print()
print('Name and Email Address Catalog')
print('------------------------------')
print('1. Look up an email address')
print('2. Add a new email address')
print('3. Change an email address')
print('4. Delete an email address')
print('5. Quit the program')
print()
choice = int(input('Enter the choice: '))
while choice < LOOK_UP or choice > QUIT:
choice = int(input('Enter a valid choice: '))
return choice
def lookUp(emails):
name = input('Enter a name: ')
print(emails.get(name, 'Not found.'))
def add(emails):
name = input('Enter a name: ')
address = input('Enter an email address: ')
if name not in emails:
emails[name] = address
pickle.dump(emails, open("emails.dat", "wb"))
else:
print('That entry already exists.')
def change(emails):
name = input('Enter a name: ')
if name in emails:
address = input('Enter the new address: ')
emails[name] = address
pickle.dump(emails, open("emails.dat", "wb"))
else:
print('That name is not found.')
def delete(emails):
name = input('Enter a name: ')
if name in emails:
del emails[name]
else:
print('That name is not found.')
main()
我知道我應該把我的電子郵件變量是某種形式和pickle.load的,但我無法弄清楚了我的生活。 mMyUtils是我爲嘗試/除邏輯之外製作的一個庫,一旦我獲得了新的東西,我就會把它放入其中。
使用json,它更安全 –
一般來說,你應該做的一件事是確保你正在關閉你正在編寫的文件,一種方法是用'with'語句打開它,所以: (「emails.dat」,「wb」)作爲infile:''pickle.dump(emails,infile)'' – jdotjdot