NotADirectoryError

In Python, NotADirectoryError is a built-in exception that occurs when an operation should act on a directory but it’s applied to a file.

As a developer, you can use this exception to handle situations where code wrongly assumes a path to be a directory and take corrective actions such as informing the user or skipping the erroneous path.

NotADirectoryError Occurs When

  • Attempting to open a file path as if it were a directory
  • Listing contents of a path without verifying if it’s a directory
  • Navigating through a file system and encountering an unexpected file in place of a directory

NotADirectoryError Example

An example of when the exception appears:

Python
>>> import pathlib
>>> list(pathlib.Path("/etc/bashrc").iterdir())
Traceback (most recent call last):
    ...
NotADirectoryError: [Errno 20] Not a directory: '/etc/bashrc'

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

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


By Leodanis Pozo Ramos • Updated May 22, 2025