我想在讀取文件時控制異常,但我遇到了問題。我是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
而且沒有下一個文件繼續。程序如何仍然可以讀取所有文件?
如果不想讓程序退出,請不要調用'sys.exit()'。 – Goyo