Python Program to Safely Create a Nested Directory

There are different ways to create a nested directory in different versions of python. Using the codes below, directories are created as shown in the image below.

Directory Structure
Directory Structure

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.

Leave a Reply

Your email address will not be published. Required fields are marked *