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)

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')

The result will be the same as the previous one.