benpay benpay - 9 months ago 50
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 = ""
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")
with infile:
content =

return content

And from another class I tell it:

read = Read()

Buy only print this one:

turn on
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 Source

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 =

The file will be closed automatically after the with block.