Skip to main content

How to Create a Folder and Its Parent Folders in Python with Path.mkdir

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
<path>.mkdir(parents=True, exist_ok=False)
PartWhat it means
<path>The folder to create, as a Path
parents=TrueAlso creates the missing folders above it
exist_ok=FalseThe 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:

make_folders.py
from pathlib import Path

target = Path("backups") / "2026-11-28"
target.mkdir(parents=True)
print(target, "is a folder:", target.is_dir())

The make_folders.py script in a macOS-style code window: target is backups/2026-11-28, created with mkdir(parents=True), then checked with is_dir.

Step 2: Run It​

Terminal
uv run python make_folders.py
Output
backups/2026-11-28 is a folder: True

The script's output in a terminal: backups/2026-11-28 is a folder: True.

One call created backups and, inside it, 2026-11-28.

Common Mistakes​

MistakeWhat happensDo this instead
Running it againThe 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 missingmkdir 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​

SymptomLikely causeFix
FileExistsErrorThe folder already exists and exist_ok is FalseUse 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​