NotADirectoryError is raised when a directory operation is attempted on a path that is not a directory. It is a subclass of OSError. This commonly happens when a file path is passed where a directory path is expected.
Why it happens
- •Calling os.listdir() or Path.iterdir() on a file path.
- •Using os.chdir() with a path pointing to a file.
- •A path component in a longer path resolves to a file instead of a directory.
- •Passing the wrong variable to a function that expects a directory.
Examples
Code that triggers the error
import os
os.listdir("myfile.txt") # it's a file, not a directoryError output
NotADirectoryError: [Errno 20] Not a directory: 'myfile.txt'
How to fix it
Always validate paths with Path.is_dir() before performing directory operations. Use pathlib for clearer path handling. When building paths dynamically, verify each component to detect unexpected file-vs-directory mismatches early.
Fixed code
from pathlib import Path
p = Path("myfile.txt")
if p.is_dir():
for item in p.iterdir():
print(item)
else:
print(f"{p} is not a directory")Related errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free