Skip to content

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.

This exception inherits from the OSError class and corresponds to the ENOTDIR system error, which is why the traceback shows [Errno 20].

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 invalid 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

Opening or traversing a non-directory file as if it were a directory raises NotADirectoryError on most POSIX platforms. On every platform, the trigger is the same: requesting a directory operation, such as os.listdir(), on something that isn’t a directory.

NotADirectoryError Example

An example of when the exception appears:

Language: Python
>>> import pathlib

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

This error indicates that the path exists but points to a file, not 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:


By Leodanis Pozo Ramos • Updated Aug. 17, 2026