python中的异常停止读取文件
我试图在读取文件时控制异常,但我遇到了一个问题。我是Python新手,我还无法控制如何捕获异常并继续从正在访问的文件中读取文本。这是我的代码:python中的异常停止读取文件,python,exception,Python,Exception,我试图在读取文件时控制异常,但我遇到了一个问题。我是Python新手,我还无法控制如何捕获异常并继续从正在访问的文件中读取文本。这是我的代码: import errno import sys class Read: #FIXME do immutables this 2 const ROUTE = "d:\Profiles\user\Desktop\\" EXT = ".txt" def setFileReaded(self, fileToRead):
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()
将优雅地终止Python脚本。在代码中,当捕获到FileNotFoundError
异常时,将调用此函数。此后将不会再运行任何操作,因为脚本将终止。因此,不会读取任何其他文件
需要指出的另一点是,您在读取文件后关闭该文件,当您像这样打开它时,这是不需要的:
以open('myfile.txt')作为f的:
content=f.read()
在使用
块执行操作后,文件将自动关闭。要准确理解您在这里提出的问题有点困难,但我将尝试提供一些提示
sys.exit()
将优雅地终止Python脚本。在代码中,当捕获到FileNotFoundError
异常时,将调用此函数。此后将不会再运行任何操作,因为脚本将终止。因此,不会读取任何其他文件
需要指出的另一点是,您在读取文件后关闭该文件,当您像这样打开它时,这是不需要的:
以open('myfile.txt')作为f的:
content=f.read()
使用块执行操作后,文件将自动关闭。如果不希望程序退出,请不要调用sys.exit()
。如果不希望程序退出,请不要调用sys.exit()
。