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 indicates that the target of a file operation is actually a directory.
As a developer, you might encounter this exception when performing file operations—such as reading, writing, or deleting a file—but mistakenly targeting 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
These triggers describe POSIX behavior. On Windows, opening a directory with open() raises PermissionError with [Errno 13] instead, because the Windows API reports the failure as an access-denied error.
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.")
...
The specified path is a directory.
Related Resources
Tutorial
How to Get a List of All Files in a Directory With Python
In this tutorial, you'll be examining a couple of methods to get a list of files and folders in a directory with Python. You'll also use both methods to recursively list directory contents. Finally, you'll examine a situation that pits one method against the other.
For additional information on related topics, take a look at the following resources:
- Listing All Files in a Directory With Python (Course)
- Build a Python Directory Tree Generator for the Command Line (Tutorial)
- Python Exceptions: An Introduction (Tutorial)
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- Working With Files in Python (Tutorial)
- Working With Python's Built-in Exceptions (Course)
- How to Get a List of All Files in a Directory With Python (Quiz)
- 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)
- Working With Files in Python (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 16, 2026