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.
Python code
20 linesfrom 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
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
- Use path.mkdir(exist_ok=True, parents=False) when you only need a single directory level
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.