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:
>>> import pathlib
>>> list(pathlib.Path("/etc/bashrc").iterdir())
Traceback (most recent call last):
...
NotADirectoryError: [Errno 20] Not a directory: '/etc/bashrc'
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:
- Python's pathlib Module: Taming the File System (Tutorial)
- Python Exceptions: An Introduction (Tutorial)
- Listing All Files in a Directory With Python (Course)
- Using Python's pathlib Module (Course)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
By Leodanis Pozo Ramos • Updated May 22, 2025