Use Path("my_folder").is_dir() from Python’s built-in pathlib module (or os.path.isdir("my_folder")) to verify both that the path exists and that it is specifically a directory—avoiding exists(), which also returns True for regular files.
Basic Example
import os
from pathlib import Path
folder = Path("data/exports")
# 1. Recommended (modern Python 3.4+): Path.is_dir()
if folder.is_dir():
print(f"Directory exists: {folder}")
else:
print(f"Directory not found: {folder}")
# 2. Classic string-path alternative: os.path.isdir()
if os.path.isdir("data/exports"):
print("Directory exists via os.path")
# 3. Best practice if your goal is to create it when missing (avoids race conditions)
folder.mkdir(parents=True, exist_ok=True)
Key Details & Edge Cases
is_dir()vs.exists():Path("foo").exists()andos.path.exists("foo")returnTrueeven if"foo"is a regular file, which can causeNotADirectoryErrororFileExistsErrorwhen you later try to write files inside it. Always useis_dir()when you specifically expect a directory.
- Avoid TOCTOU (Time-of-Check to Time-of-Use) race conditions when creating folders:
- Instead of writing
if not folder.is_dir(): folder.mkdir(), callfolder.mkdir(parents=True, exist_ok=True)(oros.makedirs("data/exports", exist_ok=True)). It creates missing parent folders atomically and succeeds silently if the directory already exists—while still raisingFileExistsErrorif a regular file already occupies that path.
- Instead of writing
- Symlink behavior (
is_dir()vs.is_symlink()):- Both
Path.is_dir()andos.path.isdir()follow symbolic links by default, returningTruefor a symlink pointing to an existing directory (andFalsefor broken symlinks). If you must reject symlinks and check for a real directory only, combine withnot folder.is_symlink()(folder.is_dir() and not folder.is_symlink()).
- Both
- Expanding
~home directories and environment variables:- Neither
Path("~/projects").is_dir()noros.path.isdir("~/projects")expands~automatically—both treat~as a literal directory name and returnFalse. Call.expanduser()first:Path("~/projects").expanduser().is_dir().
- Neither
- Permission errors (
PermissionErrorvs.False):- If a parent directory lacks execute/search permissions,
Path.is_dir()returnsFalseon most platforms (suppressingOSError/PermissionError) rather than raising an exception.
- If a parent directory lacks execute/search permissions,
Comparison of Directory Existence Checks in Python
| Method | Module | Returns True for Regular Files? |
Follows Symlinks? | Best Used When |
|---|---|---|---|---|
Path(p).is_dir() |
pathlib |
No (False) |
Yes | Modern object-oriented path handling (recommended default). |
os.path.isdir(p) |
os.path |
No (False) |
Yes | Working with legacy codebases or raw string paths without Path wrapping. |
Path(p).exists() |
pathlib |
Yes (True) |
Yes | Checking whether any filesystem entry (file or folder) occupies the path. |
Path(p).mkdir(parents=True, exist_ok=True) |
pathlib |
Raises FileExistsError |
N/A (creates dir) | Ensuring a directory exists before writing output files into it. |
You must log in or register to comment.
