Write a Python Program to Safely Create a Nested Directory

Creating nested directories in Python is a common task that can be accomplished using the os module.

However, it is important to ensure that the directory path you are trying to create is valid and does not already exist.

In this tutorial, we will discuss how to safely create a nested directory in Python.


To create a nested directory, you can use the os.makedirs() function.

This function creates a directory recursively, i.e., it creates any necessary intermediate directories.

The function takes two arguments: the first is the path of the directory you want to create, and the second is the mode in which the directory should be created.

Here’s an example of how to create a nested directory using os.makedirs():

import os

directory = "/path/to/my/directory"

try:
    os.makedirs(directory)
    print(f"Directory {directory} created successfully.")
except FileExistsError:
    print(f"Directory {directory} already exists.")
except Exception as e:
    print(f"Error occurred while creating directory: {e}")

In the example above, we first define the directory path we want to create.

We then use a try-except block to catch any errors that may occur while creating the directory.

If the directory already exists, we catch the FileExistsError exception and print a message to indicate that the directory already exists.

If any other exception occurs, we catch it and print an error message.

It is important to use a try-except block when creating directories to handle any errors that may occur.

For example, if the parent directory in the path does not exist, os.makedirs() will raise a FileNotFoundError exception.

In addition to catching exceptions, you should also ensure that the directory path you are trying to create is valid.

For example, you should ensure that the directory path does not contain any invalid characters or characters that are not allowed in directory names.

You can use the os.path.normpath() function to normalize the path and remove any redundant separators or references to the current or parent directories.


In conclusion, creating nested directories in Python is a simple task that can be accomplished using the os.makedirs() function.

However, it is important to ensure that the directory path you are trying to create is valid and does not already exist.

By using a try-except block and validating the directory path, you can safely create nested directories in your Python scripts.