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.
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.
This is the pathlib equivalent of mkdir -p on Unix-like systems.
Why Both Flags Matter
These two flags solve different problems:
- '
parents=Truecreates missing parent directories' - '
exist_ok=Trueprevents 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:
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.
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:
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:
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=Truewhen the path contains missing intermediate directories. - Forgetting
exist_ok=Truewhen reruns should succeed without error. - Assuming
exist_ok=Truewill also ignore the case where a file exists at that path. - Building paths by string concatenation instead of using
Pathoperations. - 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=Truecreates missing parents, andexist_ok=Trueignores an existing directory.' - A file at the same path still raises an error, which is usually correct.
- '
pathlibmakes cross-platform path handling cleaner than manual strings.' - Keep real filesystem failures visible instead of assuming every
mkdirissue is harmless.
Related reading
- Python PCA on Matrix too large to fit into memory
- Python pip install fails invalid command egg_info
- Python produce to different Kafka partition
- Python Progress Bar
- Python progression path - From apprentice to guru
- Python pyzmq program stucks
- Python raise from usage
- Python Ramer-Douglas-Peucker RDP algorithm with number of points instead of epsilon
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.