IOPython Error

NotADirectoryError

NotADirectoryError: [Errno 20] Not a directory

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    os.listdir("/etc/hosts")  # it's a file, not a directory
NotADirectoryError: [Errno 20] Not a directory

What causes this error

A directory operation was attempted on something that is not a directory. A path component expected to be a directory is a regular file instead.

How to fix it

Verify the path is a directory with `os.path.isdir()` or `Path.is_dir()` before calling directory operations like `os.listdir()`. Ensure path components resolve to the expected types.

Code that causes this error

Broken
import os
os.listdir("/etc/hosts")  # it's a file, not a directory

Fixed code

Fixed
import os

path = "/etc/hosts"
if os.path.isdir(path):
    print(os.listdir(path))
else:
    print(f"{path} is not a directory")

About NotADirectoryError

A NotADirectoryError is raised when a directory operation is requested on a path that is not a directory. This is a subclass of OSError and appears in scenarios like using `os.listdir()` on a file path, or when a path component that should be a directory is actually a regular file. For example, if you have a file named 'data' and try to access 'data/file.txt', Python raises NotADirectoryError because 'data' is not a directory.

This error is less common than its counterpart IsADirectoryError but appears in file traversal code, path manipulation utilities, and when filesystem structures do not match the expected layout. Validating paths with `os.path.isdir()` or `pathlib.Path.is_dir()` before directory operations prevents this error.

Common scenarios

1

Opening files with incorrect or relative paths

2

Reading files that have been moved, renamed, or deleted

3

Writing to directories instead of files or vice versa

4

Working with file streams that have been closed prematurely

Related errors