How to Create a Nested Directory in Python?

Estimated read time 2 min read

You can create a nested directory in Python by using the os module to create directories recursively. Here’s an example:

import os

# Define the path to the parent directory
parent_dir = '/path/to/parent/directory'

# Define the subdirectories to create
subdirs = ['subdir1', 'subdir2', 'subdir3']

# Use os.makedirs to create nested directories
for subdir in subdirs:
    os.makedirs(os.path.join(parent_dir, subdir), exist_ok=True)

In this example, we first define the path to the parent directory and a list of subdirectories we want to create. We then use a for loop to iterate over each subdirectory and use the os.makedirs function to create the directory.

The os.makedirs function takes two arguments: the path to the directory you want to create, and a flag (exist_ok) that indicates whether or not the function should raise an exception if the directory already exists. By setting exist_ok=True, we tell the function to not raise an exception if the directory already exists.

By using the os.path.join function to join the parent directory path and the subdirectory name, we ensure that the subdirectory is created as a child of the parent directory. The os.makedirs function will create all the intermediate directories as needed, so you can use this approach to create arbitrarily nested directories.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply