I was looking through some example of how to read multiple files of data and come across these codes pop-up a lot:
try:
...
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
But I couldn't see anyone trying to explain it so I was hoping if you guys can help me to understand what it is?
Here is an example:
import glob
import errno
...
#Create a list of the path of all .txt files
files_list = glob.glob(data_path)
#Iterate through the files in files_list
for file_name in files_list:
try:
#something
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
Here, we'll go through these lines of code one by one.
except IOError as exc:
The above line just catches an exception and gets the error message in the variable exc
. What the exception means is along the lines of
when a system function returns a system-related error, including I/O failures such as “file not found” or “disk full” (not for illegal argument types or other incidental errors). Python 3 Docs
Note in Python 3, this is now OSError
as IOError
is merged into it.
if exc.errno != errno.EISDIR:
This line will check the type of error. This is given by the error's errno
attribute. Specifically, errno.EISDIR
means the error given came because the 'file' was actually a folder / directory. More info can be found here :D.
raise
Now the if statement has gone through and checked the type of error. It only lets it through to the raise
over here if the error type does NOT mean that the path given was a directory. This means the exception could mean anything from 'Permission Denied' to 'Out of Memory'.
Hope that helped you out :D