2016-11-11 126 views
0

我想在讀取文件時控制異常,但我遇到了問題。我是Python的新手,我還無法控制如何捕捉異常,並繼續從我正在訪問的文件中讀取文本。這是我的代碼:異常停止讀取文件python

import errno 
import sys 

class Read: 
    #FIXME do immutables this 2 const 
    ROUTE = "d:\Profiles\user\Desktop\\" 
    EXT = ".txt" 

    def setFileReaded(self, fileToRead): 
     content = "" 
     try: 
      infile = open(self.ROUTE+fileToRead+self.EXT) 
     except FileNotFoundError as error: 
      if error.errno == errno.ENOENT: 
       print ("File not found, please check the name and try again") 
      else: 
       raise 
      sys.exit() 
     with infile: 
      content = infile.read() 
      infile.close() 

     return content 

而且從另一個類我告訴它:

read = Read() 
print(read.setFileReaded("verbs")) 
print(read.setFileReaded("object")) 
print(read.setFileReaded("sites")) 
print(read.setFileReaded("texts")) 

購買只打印這一項:

turn on 
connect 
plug 
File not found, please check the name and try again 

而且沒有下一個文件繼續。程序如何仍然可以讀取所有文件?

+0

如果不想讓程序退出,請不要調用'sys.exit()'。 – Goyo

回答

2

這裏有點難以理解你究竟在問什麼,但我會嘗試提供一些指示。

sys.exit()將優雅地終止Python腳本。在你的代碼中,當FileNotFoundError異常被捕獲時調用這個函數。在此之後沒有進一步的行動,因爲你的腳本將會終止。所以其他文件都不會被讀取。

另外要指出的是你要關閉看完後的文件,該文件不需要當你打開它就像這樣:

with open('myfile.txt') as f: content = f.read()

文件將自動with後關閉塊。

+1

是的,就是這樣!它解決了我的問題,謝謝! – benpay