all Python 3Exceptionsexception
OSError
built-in exceptions
The base class for operating system errors: files, network, processes. FileNotFoundError and PermissionError are its subclasses.
Syntax
raise OSError(errno, strerror)
Catch OSError itself only as a safety net: it covers dozens of unrelated failures, and an except clause is almost always sharper when it names the concrete subclass — FileNotFoundError, PermissionError, IsADirectoryError. When you really need to branch on the cause, use the errno, strerror and filename attributes, and compare errno against constants from the errno module rather than parsing the message, which varies by OS and locale. The old names IOError and EnvironmentError have been plain aliases of OSError since Python 3.3, not separate classes.
Examples
import errno, os, tempfile
with tempfile.TemporaryDirectory() as d:
box = os.path.join(d, 'box')
os.mkdir(box)
try:
os.mkdir(box)
except FileExistsError as e: # подкласс OSError — ловим точно
print(e.errno == errno.EEXIST, os.path.basename(e.filename)) # → True box
try:
os.remove(os.path.join(d, 'no_file'))
except OSError as e: # последняя сетка: причину различает errno, а не текст
print(type(e).__name__, e.errno == errno.ENOENT) # → FileNotFoundError True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy