How do you check if a folder or directory already exists in Python? | A1Lab@MZeeshanM to PythonEnglish • 5 days ago

How do you check if a folder or directory already exists in Python?

message-square
0

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() and os.path.exists("foo") return True even if "foo" is a regular file, which can cause NotADirectoryError or FileExistsError when you later try to write files inside it. Always use is_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(), call folder.mkdir(parents=True, exist_ok=True) (or os.makedirs("data/exports", exist_ok=True)). It creates missing parent folders atomically and succeeds silently if the directory already exists—while still raising FileExistsError if a regular file already occupies that path.
  • Symlink behavior (is_dir() vs. is_symlink()):
    • Both Path.is_dir() and os.path.isdir() follow symbolic links by default, returning True for a symlink pointing to an existing directory (and False for broken symlinks). If you must reject symlinks and check for a real directory only, combine with not folder.is_symlink() (folder.is_dir() and not folder.is_symlink()).
  • Expanding ~ home directories and environment variables:
    • Neither Path("~/projects").is_dir() nor os.path.isdir("~/projects") expands ~ automatically—both treat ~ as a literal directory name and return False. Call .expanduser() first: Path("~/projects").expanduser().is_dir().
  • Permission errors (PermissionError vs. False):
    • If a parent directory lacks execute/search permissions, Path.is_dir() returns False on most platforms (suppressing OSError / PermissionError) rather than raising an exception.

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.