Python Program - Safely Create a Nested Directory

https:‮//‬www.theitroad.com

here's a Python program that safely creates a nested directory:

import os

# define a function to create a nested directory
def make_nested_dir(path):
    try:
        os.makedirs(path)
    except OSError as e:
        if not os.path.isdir(path):
            raise

# get the path to the nested directory from user
path = input("Enter path to nested directory: ")

# call the make_nested_dir function
make_nested_dir(path)

# print a message indicating that the directory was created
print("Nested directory created successfully!")

In this program, we first import the os module using the import keyword.

We then define a function called make_nested_dir that takes a path as input and creates a nested directory at that path. We use the os.makedirs() function to create the directory, and catch any OSError exceptions that occur. If the exception is caused by the directory already existing, we simply ignore it. If the exception is caused by some other error, we raise the exception so that it can be handled by the calling code.

We then use the input() function to get the path to the nested directory from the user, and store it in the variable path.

We then call the make_nested_dir() function with the path path.

Finally, we print out a message using the print() function to indicate that the directory was created successfully.