How to Create a Folder and Its Parent Folders in Python with Path.mkdir
Saving a file into backups/2026-11-28 fails when those folders don't exist yet. Path.mkdir(parents=True) creates the folder and every missing folder above it in one call. This guide creates two levels at once, with real output from Python 3.15.2.
Syntax
<path>.mkdir(parents=True, exist_ok=False)
| Part | What it means |
|---|---|
<path> | The folder to create, as a Path |
parents=True | Also creates the missing folders above it |
exist_ok=False | The default: a folder that's already there raises FileExistsError. True accepts it |
Python's pathlib reference: "Create a new directory at this given path." And: "If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command)."
Prerequisites
- uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
Neither backups nor backups/2026-11-28 exists yet:
from pathlib import Path
target = Path("backups") / "2026-11-28"
target.mkdir(parents=True)
print(target, "is a folder:", target.is_dir())

Step 2: Run It
uv run python make_folders.py
backups/2026-11-28 is a folder: True

One call created backups and, inside it, 2026-11-28.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Running it again | The folder exists now: FileExistsError: [Errno 17] File exists: 'backups/2026-11-28' | Add exist_ok=True when the folder may already be there; it then ran without an error |
Leaving out parents=True when the parent is missing | mkdir creates only the last folder: Path("other").joinpath("2026").mkdir() raised FileNotFoundError: [Errno 2] No such file or directory: 'other/2026' | Pass parents=True |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
FileExistsError | The folder already exists and exist_ok is False | Use a new name, or pass exist_ok=True |
FAQ
When is the error useful?
When every run should get a folder of its own, such as a backup named after the time: an error means two runs picked the same name.
Conclusion
target.mkdir(parents=True) created backups and backups/2026-11-28 in one call. A second run raised FileExistsError, which exist_ok=True turns off.
Additional Resources
- Path.mkdir —
parents,exist_okandmode.
