2011-08-20 38 views
-2

在函數check_price()我試圖打開一個不存在的.txt文件來讀取和 我想用except語句來捕獲IOerror。除了語句

但之後,我創建了一個.txt文件,並且我想使用相同的函數來讀取它。但是,我的功能不讀取文件。誰能幫我?

我想做一個價格檢查程序。

樣品看起來像這樣。

Menu: 
(I)nstructions 
(L)oad Products 
(S)ave Products 
(A)dd Product 
(C)heck Prices 
(Q)uit 
>>> C 
No products. 

Menu: 
(I)nstructions 
(L)oad Products 
(S)ave Products 
(A)dd Product 
(C)heck Prices 
(Q)uit 
>>> L 
Enter file name: products.txt 

Menu: 
(I)nstructions 
(L)oad Products 
(S)ave Products 
(A)dd Product 
(C)heck Prices 
(Q)uit 

>>> c 
Huggies is $0.39 per unit. 
Snugglers is $0.26 per unit. 
Baby Love is $0.23 per unit. 

我的功能:

def check_price(): 
     while True: 
      try: 
       text_file = open("product.txt",'r') 
       break 
      except IOError: 
       print"no product" 
       text_file = open("product.txt",'r') 
       line = text_file.readline() 
       if line == "": 
        break 
       print "" 
+0

爲什麼'while True'?無法弄清楚。 – Tom

回答

0

你說的不讀取文件是什麼意思?那麼,爲什麼break聲明之後有代碼?

我想既然你做出了錯誤的壓痕給出線以下的break聲明相同縮進的except塊,而他們應該已經在except塊與縮進較低水平之後出現在文件不被讀取。 嘗試將該額外的代碼移入try塊或刪除額外的文件打開並減少代碼縮進級別。

我認爲你的錯誤是因爲你忘記了break退出while循環的當前迭代以及它不會被執行後的所有代碼。

0

成功打開文件後沒有任何代碼可以運行。 break之後的所有代碼仍然是except:塊的一部分。修復你的縮進。

-1

該功能是無意義的。沒有理由在這裏使用while循環。特別是,邏輯看起來很容易進入無限循環。

以下是一些建議:

  1. 我會避免在try /除外,只是直接檢查文件是否存在,使用os.path.exists

  2. 如果該文件尚不存在,請創建它。使用「r」打開並不會自動創建文件。請參閱open()的文檔。我想你想在這裏使用「w」,只是爲了強制文件創建。但是,如果文件尚不存在,您只想執行此操作,否則會截斷該文件。

3

有兩個問題。一個是你打開文件的地方,另一個是使用while語句打開文件。如果你從邏輯上思考問題,那麼你真的不想重新打開和關閉那個文件。只需打開一次,從中讀取每一行,然後關閉它。所以你的閱讀功能可能是這樣的:

def check_price(file_path): 

    # try and open the file. If there's an exception, return an error 
    try: 
     f = open(filepath, "r") 
    except IOError as e: 
     # do something with e, possibly. 
     # could return an error code? 
     # could raise an exception? 
     # could not do anything and let the parent function 
     # handle the exception: 
     return -1 

    # read until no more lines appear 
    while True: 
     line = f.readline() 
     if not line: # not x is true in python for False, "", [] 
      break 

     # process that line 

    f.close() # don't forget this 

有一些關於如何處理異常的設計問題。如果存在IOError,那麼在函數中是否在這裏處理它們,意味着異常「傳播」到上面的函數中。這個函數可能在你的用戶界面中,這樣的錯誤信息應該被處理。在這樣的功能中處理它們的問題是,您必須保留自己的異常錯誤代碼列表,從而增加了維護負擔...對您而言,這是一個負擔。

我應該指出處理文件讀取的另一種方式,但是,這是更好的,並出現在較新版本的python中。這裏是:

def check_price(file_path): 

    with open(filepath, "r") as f: 
     while True: 
      line = f.readline() 
      if not line: 
       break 
      # process line 

    # here, at the same level of indentation as the with statement, 
    # f has been automatically closed for you. 

我個人喜歡這種方法。 with語句控制從open產生的f對象的生命期,使您不必記住關閉它。