IsADirectoryError
In Python, IsADirectoryError
is a built-in exception that is raised when an operation expected to be performed on a file is attempted on a directory instead.
This exception inherits from the OSError
class and is specifically used to indicate that the target of a file operation is, in fact, a directory.
As a developer, you might encounter this exception when performing file operations like reading, writing, or deleting a file but mistakenly target a directory.
IsADirectoryError
Occurs When
- Attempting to open a directory for reading or writing as if it were a file
- Trying to delete a directory using file-deletion operations
- Using file-specific operations like
open()
on a directory
IsADirectoryError
Example
An example of when the exception appears:
>>> with open("/etc", "r") as file:
... content = file.read()
...
Traceback (most recent call last):
...
IsADirectoryError: [Errno 21] Is a directory: '/etc'
Handling the exception:
>>> try:
... with open("/etc", "r") as file:
... content = file.read()
... except IsADirectoryError:
... print("The specified path is a directory.")
...
Related Resources
Tutorial
Python Exceptions: An Introduction
In this beginner tutorial, you'll learn what exceptions are good for in Python. You'll see how to raise exceptions and how to handle them with try ... except blocks.
For additional information on related topics, take a look at the following resources:
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- Working With Files in Python (Tutorial)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Practical Recipes for Working With Files in Python (Course)
By Leodanis Pozo Ramos • Updated May 22, 2025