Algorithm


  1. Input:

    • Accept the path of the nested directory as input from the user or as an argument.
  2. Check if the Directory Already Exists:

    • Use the os.path.exists() function to check if the specified directory already exists.
  3. Create Directory if Not Exists:

    • If the directory doesn't exist, use the os.makedirs() function to create the nested directory along with any missing parent directories.
  4. Handle Errors:

    • Handle exceptions that may occur during the directory creation process, such as permissions issues or invalid paths.
  5. Output/Result:

    • Display a message indicating whether the directory was successfully created or if it already exists.

 

Code Examples

#1 Code Example- Using pathlib.Path.mkdir

Code - Python Programming

from pathlib import Path

p = Path('/root/directoryA/directoryB')
p.mkdir(parents = True, exist_ok = True)
Copy The Code & Try With Live Editor

#2 Code Example- Using os.makedirs

Code - Python Programming

import os

os.makedirs('/root/directoryA/directoryB')
Copy The Code & Try With Live Editor

#3 Code Example- Using distutils.dir_util

Code - Python Programming


import distutils.dir_util

distutils.dir_util.mkpath('/root/directoryA/directoryB')
Copy The Code & Try With Live Editor

#4 Code Example- Raising an exception if the directory already exists

Code - Python Programming


import os

try:
    os.makedirs('/directoryA/directoryB')
except FileExistsError:
    print('File already exists')
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Python Programing Example to Safely Create a Nested Directory-DevsEnv