In Python 3, IOError is an alias of OSError. To verify, run the code:
IOError is OSError
---
True
OSError is the parent class of the file I/O exceptions.
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
OSError.__subclasses__()
---
[ConnectionError,
BlockingIOError,
ChildProcessError,
FileExistsError,
FileNotFoundError,
IsADirectoryError,
NotADirectoryError,
InterruptedError,
PermissionError,
ProcessLookupError,
TimeoutError,
io.UnsupportedOperation,
signal.ItimerError,
socket.herror,
socket.gaierror,
socket.timeout,
ssl.SSLError,
shutil.Error,
shutil.SpecialFileError,
shutil.ExecError,
shutil.ReadError,
urllib.error.URLError,
gzip.BadGzipFile]
Hence, catch the OSError and check the exact class if detail is requied.
try:
with open('hoge') as f:
pass
except OSError as e:
print(f"{type(e)}: {e}")
---
<class 'FileNotFoundError'>: [Errno 2] No such file or directory: 'hoge'
try
might be worth it. This can be done withos.path.exists(file)
andos.access(file, os.R_OK)
respectively. Such check can never be free from a race condition though but vanishing files are seldom a normal circumstance ;)pathlib
module, which makes this problem a lot easier, and should probably be standard Python practice (especially since it was also backported to 2.7).IOError
, it does not catchcsv.Error
due to file not being CSV format whenDialect.strict=True
orError
for any other errors (according to CSV package docs), so an outer try, or just simply checking for file exists, then an inner try for CSV exceptions is probably the right answer.