A lot of people who know to program do not realize how much work they do manually. Like, making folder manually if it has a well-defined structure.

So Why not use the power of programming. Automation in python is a piece of cake.

That’s enough talk. Let’s see how can we automate the whole thing.

Suppose we want to create a directory structure as shown in the below image.

Let’s import all necessary modules

from pathlib import Path

Now we will define the structure of the directory. Python dictionary is the best way to implement this structure and it is similar to the JSON object in javascript. We will create a nested dictionary to define parent and child directories. The empty list represents that there is no more further structure and This is the last folder. We also need to specify the path where we are going to create a directory structure.

parent_dir = r"C:\Users\win\OneDrive\Desktop"

structure = {
    "India" : {
        "Noida" : {
            "Sector 62" : []
        },
        "Delhi" : {
            "Connaught Place": [],
            "Laxmi Nagar": []
        }
    }
}

Let’s make a recursive function that will traverse the structure dictionary until all branches are covered. In this example there are 3 branches

  1. India -> Noida -> Sector 62
  2. India -> Delhi -> Connaught place
  3. India -> Delhi -> Laxmi Nagar
def recursive_path(data, path=''):
    path_list = []
    for key in data:
        temp_path = f"{path}/{key}"
       
        if isinstance(data[key], list):
            path_list.append(temp_path) 
        else:
            path_list.extend(recursive_path(data[key],temp_path))
    return path_list
            
list_of_path = recursive_path(structure)  
print(list_of_path)

Output:

['/India/Noida/Sector 62', '/India/Delhi/Connaught Place', '/India/Delhi/Laxami Nagar']

Now we will loop over the complete path. Now pathlib module comes into the picture. It creates folders mentioned in the path. If a folder already exists it skips that. It does it in one line of code that’s saves an extra function.

for sub_path in list_of_path:
    Path(parent_dir+sub_path).mkdir(parents=True, exist_ok=True) 

Now Let’s combine the whole code and see the magic

from pathlib import Path

structure = {
    "India" : {
        "Noida" : {
            "Sector 62" : []
        },
        "Delhi" : {
            "Connaught Place": [],
            "Laxami Nagar": []
        }
    }
}


parent_dir = r"C:\Users\win\OneDrive\Desktop"

def recursive_path(data, path=''):
    path_list = []
    for key in data:
        temp_path = f"{path}/{key}"
       
        if isinstance(data[key], list):
            path_list.append(temp_path) 
        else:
            path_list.extend(recursive_path(data[key],temp_path))
    return path_list
            
list_of_path = recursive_path(structure)  

for sub_path in list_of_path:
    Path(parent_dir+sub_path).mkdir(parents=True, exist_ok=True) 

I hope this post helped you to save some time.