Python Program to Safely Create a Nested Directory

Example 1: Using pathlib.Path.mkdir

For python 3.5 and above, you can use pathlib.Path.mkdir.

from pathlib import Path

Path("/root/dirA/dirB").mkdir(parents=True, exist_ok=True)

You should provide the full path (absolute path) of the directory (not relative path). If the directory already exists, the above code does not raise an exception.


Example 2: Using os.makedirs

For python 3.2 and above, you can use os.makedirs.

import os

 

os.makedirs("/root/dirA/dirB")

You should provide the full path (absolute path) of the directory (not relative path). If the directory already exists, the above code does not raise an exception.


Example 3: Using distutils.dir_util

import distutils.dir_util

 

distutils.dir_util.mkpath("/root/dirA/dirB")

You should provide the full path (absolute path) of the directory (not relative path). If the directory already exists, the above code does not raise an exception.


Example 4: Raising an exception if directory already exists

import os

 

try:

    os.makedirs("/dirA/dirB")

except FileExistsError:

    print("File already exists")

If the directory already exists, then FileExistsError is raised.

 


0 Comments