2012-12-18 52 views
1

在我的簡介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是我爲嘗試/除邏輯之外製作的一個庫,一旦我獲得了新的東西,我就會把它放入其中。

+0

使用json,它更安全 –

+0

一般來說,你應該做的一件事是確保你正在關閉你正在編寫的文件,一種方法是用'with'語句打開它,所以: (「emails.dat」,「wb」)作爲infile:''pickle.dump(emails,infile)'' – jdotjdot

回答

1

如果保存字典,像這樣:

pickle.dump(emails, open('emails.dat', 'wb')) 

下面將載入它:

emails = pickle.load(open('emails.dat', 'rb')) 
1

必須加載該文件,unpickle數據之前,您可以訪問它,改變lookUp()這樣:

def lookUp(emails): 
    with open("emails.dat", "rb") as fo: 
     emails = pickle.load(fo) 

    name = input('Enter a name: ') 
    print(emails.get(name, 'Not found.')) 
0

問題是,我想我沒有重視它è如果字典不在第一位,那就是我應該做的事情。設計文檔指出,每次運行程序時都應該加載字典。那麼如果你第一次運行這個程序,你沒有加載字典,導致錯誤。我通過基本上使用try/except兩次執行函數來解決這個問題。

我的代碼:

import mMyUtils 
import pickle 
import dictionaryGenerator 
LOOK_UP = 1 
ADD = 2 
CHANGE = 3 
DELETE = 4 
QUIT = 5 

def main(): 
    hasError = False 
    try: 
     emails = pickle.load(open('emails.dat', 'rb')) 
     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: 
       print("Good-bye!") 
       exit 
    except Exception as err: 
     hasError = True 
     mMyUtils.printError("Error: no such file",err) 
     mMyUtils.writeToErrorLog() 

    finally: 
     if hasError: 
      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: 
       print("Good-bye!") 
       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 
     with open("emails.dat", "wb") as infile: 
      pickle.dump(emails, infile) 

    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 
     with open("emails.dat", "wb") as infile: 
      pickle.dump(emails, infile) 

    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() 
1

使用ast.literal_eval代替鹹菜考慮自己:http://docs.python.org/2/library/ast.html#ast.literal_eval

>>>import ast 
>>> print mydict 
{'bob': 1, 'danny': 3, 'alan': 2, 'carl': 40} 
>>> string="{'bob': 1, 'danny': 3, 'alan': 2, 'carl': 40}" 
>>> type(string) 
<type 'str'> 
>>> type(ast.literal_eval(string)) 
<type 'dict'> 

要保存/讀取文件快譯通,你可以像正常的字符串。