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


The result will be the same as the previous one.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Woo Jia Hao
Woo Jia Hao is a software developer from Singapore. He is an avid learner who...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github