Python Program to Safely Create a Nested Directory
Last Updated :
18 Apr, 2024
Creating a nested directory in Python involves ensuring that the directory is created safely, without overwriting existing directories or causing errors. To create a nested directory we can use methods like os.makedirs()
, os.path.exists()
, and Path.mkdir()
. In this article, we will study how to safely create a Nested Directory in Python.
Python Program to Safely Create a Nested Directory
Below are some of the ways and approaches by which we can create a Nested Directory using Python:
- Using os.makedirs() Function
- Using os.path.exists() Function
- Using Path.mkdir() Function
Create a Nested Directory Using os.makedirs() Function
In this example,
os.makedirs()
function is used to create a nested directory. It accepts the path of the directory to be created as input. If the directory already exists, it raises a FileExistsError and
prints a message indicating that the directory already exists but if the directory does not exist, it creates it and prints a success message.
Python3
import os
def create_nested_directory(path):
try:
os.makedirs(path)
print(f"Directory '{path}' created successfully.")
except FileExistsError:
print(f"Directory '{path}' already exists.")
# Example usage:
directory_path = "./parent_directory/child_directory"
create_nested_directory(directory_path)
OutputDirectory './parent_directory/child_directory' created successfully.
Create a Nested Directory Using os.path.exists() Function
In this example, os.path.exists()
function is used to checks if the directory already exists and if it does not exist than it creates it using os.makedirs()
.
Python3
import os
def create_nested_directory(path):
if not os.path.exists(path):
os.makedirs(path)
print(f"Directory '{path}' created successfully.")
else:
print(f"Directory '{path}' already exists.")
# Example usage:
directory_path = "./parent_directory/child_directory"
create_nested_directory(directory_path)
OutputDirectory './parent_directory/child_directory' created successfully.
Create a Nested Directory Using Path.mkdir() Function
In this example, path.mkdir()
method from the pathlib
module is used to create a directory.It accepts the path of the directory to be created as input.It checks if parents
argument is set to True thus
creating parent directories if they do not exists but If the directory already exists, it raises a FileExistsError
, which is caught by the except
block
Python3
from pathlib import Path
def create_nested_directory(path):
directory = Path(path)
try:
directory.mkdir(parents=True)
print(f"Directory '{path}' created successfully.")
except FileExistsError:
print(f"Directory '{path}' already exists.")
directory_path = "./parent_directory/child_directory"
create_nested_directory(directory_path)
OutputDirectory './parent_directory/child_directory' created successfully.
Share your thoughts in the comments
Please Login to comment...