Skip to content

How can I safely create a nested directory?

To safely create a nested directory in python, you can use the os module and the makedirs() function. This function will create all of the necessary directories in the path that you specify, including any intermediate directories that may not yet exist.

Here's an example of how to use makedirs() to create a nested directory:

os.makedirs in try-except in Python

python
import os

path = '/path/to/nested/directory'

try:
    os.makedirs(path)
except OSError:
    print('Creation of the directory failed')
else:
    print('Successfully created the directory')

This code will attempt to create the nested directory specified in path. If the directory already exists, or if there is an error creating the directory, it will print an error message. Otherwise, it will print a success message.

You can also use the exist_ok parameter of makedirs() to specify whether or not the function should raise an error if the directory already exists. For example:

od.makedir with exist_ok=True in Python

python
import os

path = '/path/to/nested/directory'

os.makedirs(path, exist_ok=True)

Dual-run preview — compare with live Symfony routes.