Skip to content

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:

Language: Python
>>> with open("/etc", "r") as file:
...     content = file.read()
...
Traceback (most recent call last):
    ...
IsADirectoryError: [Errno 21] Is a directory: '/etc'

Handling the exception:

Language: Python
>>> 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.
How to Get a List of All Files in a Directory With Python

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.

intermediate stdlib

For additional information on related topics, take a look at the following resources:

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