NotADirectoryError
PythonERRORCommonOS ErrorHIGH confidence

Not a directory

Production Risk

Common when processing user-supplied paths; always validate before directory operations.

What this means

A subclass of OSError (errno ENOTDIR) raised when a directory operation is attempted on a path that exists but is not a directory.

Why it happens
  1. 1os.listdir() or os.scandir() on a file path
  2. 2Trying to cd into a file path
  3. 3A path component that should be a directory is actually a file
How to reproduce

os.listdir() on a regular file.

trigger — this will error
trigger — this will error
import os
os.listdir('/etc/hosts')  # /etc/hosts is a file, not a directory

expected output

NotADirectoryError: [Errno 20] Not a directory: '/etc/hosts'

Fix

Verify the path is a directory before operating

WHEN Before directory operations on user-supplied paths

Verify the path is a directory before operating
import os
path = '/some/path'
if os.path.isdir(path):
    for entry in os.scandir(path):
        print(entry.name)
else:
    print(f"{path} is not a directory")

Why this works

os.path.isdir() returns True only for actual directories; use it before directory-specific operations.

Code examples
Triggerpython
import os
os.listdir("/etc/hosts")  # NotADirectoryError: Not a directory
Handle with try/exceptpython
try:
    entries = os.listdir(path)
except NotADirectoryError:
    print(f"{path} is not a directory")
Avoid with isdir() checkpython
import os
if os.path.isdir(path):
    entries = os.listdir(path)
Sources
Official documentation ↗

Python Docs — Built-in Exceptions

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors