How can I safely create a nested directory in Python?

Better Stack Team
Updated on January 24, 2023

The most common way to safely create a nested directory in Python is using the pathlib or os modules.

Using pathlib

You can create a nested directory in python 3.5 or later using the Path and mkdir method.

from pathlib import Path

p = Path('/root/directory/nested_directory')
p.mkdir(parents = True, exist_ok = True)
Copied!

An important part of the code above is the parents argument is set to True. The default value is False, meaning that if the parent directory (in this case /root/directory) is not found, an error is thrown. If we set parents to True, the error won’t be thrown and the non-existing parent directory will be created along with the nested directory.

The exist_ok arguments ensure that an error won’t be thrown when the directory already exists.

Using os.makedirs

Another possible method is to use os.makedirs function.

import os

os.makedirs('/root/directory/nested_directory')
Copied!

The result will be the same as the previous one.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack