How to Create Nested Directories with pathlib mkdir parents in Python

Create nested directories with pathlib's Path.mkdir using parents=True and exist_ok=True to avoid errors when paths already exist.

Easy Python 3.9+ Aug 9, 2026 Files & data 13 views 0 copies

Python code

20 lines
Python 3.9+
from pathlib import Path

def create_nested_directories(base_path: str, dirs: list[str]) -> None:
    for directory in dirs:
        path = Path(base_path) / directory
        path.mkdir(parents=True, exist_ok=True)
        print(f"Created: {path}")

if __name__ == "__main__":
    root = "output"
    nested_dirs = ["2024/01", "data/logs/archive", "reports/financial/2024"]

    create_nested_directories(root, nested_dirs)

    # Verify the directories exist
    for path_str in ["output/2024/01", "output/data/logs/archive", "output/reports/financial/2024"]:
        if Path(path_str).is_dir():
            print(f"Verified: {path_str} exists")
        else:
            print(f"ERROR: {path_str} missing")

Output

stdout
Created: output/2024/01
Created: output/data/logs/archive
Created: output/reports/financial/2024
Verified: output/2024/01 exists
Verified: output/data/logs/archive exists
Verified: output/reports/financial/2024 exists

How it works

The Path.mkdir(parents=True, exist_ok=True) call creates all intermediate parent directories missing from the path. The parents=True flag ensures that nested paths like output/2024/01 are created recursively, while exist_ok=True suppresses the error that would otherwise be raised when the directory already exists. Using Path(base_path) / directory joins paths in an OS-agnostic way, so the code works on Windows, macOS, and Linux. The is_dir() method verifies that each expected directory was successfully created, making the example self-checking.

Common mistakes

  • Forgetting parents=True, which raises FileNotFoundError for missing parents
  • Missing exist_ok=True when handling existing directories
  • Using string concatenation with os.sep instead of Path's / operator

Variations

  1. Use path.mkdir(exist_ok=True, parents=False) when you only need a single directory level
  2. Use os.makedirs(name, exist_ok=True) as a lower-level alternative

Real-world use cases

  • Creating dated log directories like logs/2024/01/ before writing log files.
  • Setting up project skeletons that create nested config or data folders on startup.
  • Preparing output directories for batch processing jobs that store results by category or date.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.