在 Python 3 中,IOError 是 OSError 的别名。要验证,请运行代码:
IOError is OSError
---
True
OSError 是文件 I/O 异常的父类。
+-- 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]
因此,如果需要详细信息,请捕获 OSError 并检查确切的类。
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'