Python
pathlib
directories
file system
how to

Python pathlib make directories if they don’t exist

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

With pathlib, the standard way to create a directory only when needed is Path.mkdir(parents=True, exist_ok=True). That one call handles the common cases cleanly, including nested directories and the case where the directory already exists.

The Basic Pattern

Path.mkdir() creates one directory by default. If you want missing parents created too, set parents=True. If you want the call to succeed when the directory already exists, set exist_ok=True.

python
1from pathlib import Path
2
3output_dir = Path("reports/2026/april")
4output_dir.mkdir(parents=True, exist_ok=True)
5
6print(output_dir.resolve())

This is the pathlib equivalent of mkdir -p on Unix-like systems.

Why Both Flags Matter

These two flags solve different problems:

  • 'parents=True creates missing parent directories'
  • 'exist_ok=True prevents an error if the final directory already exists'

Without parents=True, the call fails if an intermediate folder is missing. Without exist_ok=True, the call raises FileExistsError when the directory is already present.

That is why the two are so often used together.

A Small Reusable Helper

If you create output folders in several places, a tiny helper keeps the intent explicit:

python
1from pathlib import Path
2
3
4def ensure_dir(path):
5    path = Path(path)
6    path.mkdir(parents=True, exist_ok=True)
7    return path
8
9
10log_dir = ensure_dir("logs/app")
11print(log_dir)

This is clearer than repeating string-based path logic throughout the codebase.

What Happens if a File Exists There

exist_ok=True does not mean "ignore everything." It only ignores the case where the existing path is already a directory. If a regular file exists at that path, you still get an error, which is usually the correct behavior.

python
1from pathlib import Path
2
3path = Path("example")
4path.write_text("not a directory")
5
6try:
7    path.mkdir(exist_ok=True)
8except FileExistsError as exc:
9    print(exc)

That distinction is important because swallowing that case would hide real filesystem mistakes.

Why pathlib Is Better Than Manual String Handling

pathlib gives you:

  • cross-platform path joining
  • readable object-oriented code
  • easy conversion to strings only when needed

For example:

python
1from pathlib import Path
2
3base = Path.home()
4cache_dir = base / ".myapp" / "cache"
5cache_dir.mkdir(parents=True, exist_ok=True)

This is easier to read and less error-prone than building paths by concatenating strings.

Permissions and Race Conditions

Even with the right flags, directory creation can still fail because of permissions, read-only filesystems, or invalid paths. So if the directory must exist for the program to continue, let the exception surface or handle it explicitly:

python
1from pathlib import Path
2
3try:
4    Path("/root/protected-dir").mkdir(parents=True, exist_ok=True)
5except PermissionError:
6    print("permission denied")

exist_ok=True also helps with simple race conditions where two processes try to create the same directory. It is not a full concurrency protocol, but it prevents the most common "already exists" failure.

That makes it a good default in scripts that may be rerun or in tools that prepare output folders before writing logs, reports, or cache files.

Common Pitfalls

  • Forgetting parents=True when the path contains missing intermediate directories.
  • Forgetting exist_ok=True when reruns should succeed without error.
  • Assuming exist_ok=True will also ignore the case where a file exists at that path.
  • Building paths by string concatenation instead of using Path operations.
  • Hiding permission or filesystem errors that should be handled explicitly.

Summary

  • Use Path.mkdir(parents=True, exist_ok=True) to create directories only when needed.
  • 'parents=True creates missing parents, and exist_ok=True ignores an existing directory.'
  • A file at the same path still raises an error, which is usually correct.
  • 'pathlib makes cross-platform path handling cleaner than manual strings.'
  • Keep real filesystem failures visible instead of assuming every mkdir issue is harmless.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.