benpay benpay - 1 month ago 9
Python Question

exception stop read files python

I'm trying control the exceptions reading files, but I have a problem. How I'm new with python I no control yet how can I catch an exception and still reading the text files in the call. This is my code:

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


And from another class I tell it:

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


Buy only print this one:

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


And no continue with the next files. How can the program still reading all files?

Answer

It's a little difficult to understand exactly what you're asking here, but I'll try and provide some pointers.

sys.exit() will terminate the Python script gracefully. In your code, this is called when the FileNotFoundError exception is caught. Nothing further will be ran after this, because your script will terminate. So none of the other files will be read.

Another thing to point out is that you close the file after reading it, which is not needed when you open it like this:

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

The file will be closed automatically after the with block.