Use Path.mkdir(parents=True, exist_ok=True) from Python’s built-in pathlib module (or os.makedirs(path, exist_ok=True)) to create a target directory along with any missing intermediate parent directories without raising an error if the directory already exists.
Basic Example
from pathlib import Path
# 1. Define a nested directory path where parent folders may not exist yet
target_dir = Path("projects/2026/analytics/reports")
# 2. Create the target directory and all missing parent directories safely
target_dir.mkdir(parents=True, exist_ok=True)
print(target_dir.exists()) # Output: True
Key Details & Parameters
parents=True: Tells Python to create any missing intermediate directories along the path (equivalent tomkdir -pin Unix/Linux shells). Ifparents=False(the default) and a parent folder is missing, Python raises aFileNotFoundError.exist_ok=True: Prevents aFileExistsErrorif the target directory already exists. Note that if the path already exists as a regular file rather than a directory,exist_ok=Truewill still raise aFileExistsErrorto protect your file.- Creating parent folders before writing a file: A common pattern when saving output files to dynamic paths is calling
.parent.mkdir()on the file path first:output_file = Path("logs/november/app.log") output_file.parent.mkdir(parents=True, exist_ok=True) output_file.write_text("Log started\n", encoding="utf-8") - Using
os.makedirs()(string-based alternative): If you prefer working with plain string paths rather thanPathobjects, useos.makedirs():import os os.makedirs("projects/2026/analytics/reports", exist_ok=True) - Setting custom directory permissions (
mode): BothPath.mkdir()andos.makedirs()accept an optionalmodeparameter (defaulting to0, modified by the system’sumask), such astarget_dir.mkdir(mode=0o755, parents=True, exist_ok=True)on Unix/Linux systems.
Comparison of Directory Creation Methods
| Method | Creates Missing Parents? | Safe if Directory Exists? | Return Type / Style |
|---|---|---|---|
Path.mkdir(parents=True, exist_ok=True) |
Yes | Yes | Object-oriented (pathlib.Path) |
os.makedirs(path, exist_ok=True) |
Yes | Yes | String-based (os module) |
Path.mkdir() / os.mkdir(path) |
No (raises FileNotFoundError) |
No (raises FileExistsError) |
Single-level directory creation only |
You must log in or register to comment.
