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:

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:

Python
>>> try:
...     with open("/etc", "r") as file:
...         content = file.read()
... except IsADirectoryError:
...     print("The specified path is a directory.")
...

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.

basics python

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


By Leodanis Pozo Ramos • Updated May 22, 2025