[SOLVED] Python Function that take n number of arguments as list and create folder and sub folders based on their index

Issue

I am creating a python function which will take "n" numbers of arguments as list and based on their position it should create folders and nested folder
For eg.

path = Path("Path to Directory")
root_folders = ['f1','f2','f3']
yr = ['2018', '2019']
mnth = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']

"root_folders" should be main folder within "path"
"yr" should be sub-folders for each of "root_folders"
"mnth" be sub-folders for each of "yr"

I have been able to achieve this using following code:

def folder(root,*args):
    for a in args[0]:
        path = os.path.join(root, a)
        if not os.path.exists(path):
            os.mkdir(path)          
            for b in args[1]  :
                path2 = os.path.join(path, b)
                if not os.path.exists(path2):
                    os.mkdir(path2)
                for c in args[2]  :
                    path3 = os.path.join(path2, c)
                    if not os.path.exists(path3):
                        os.mkdir(path3)

folder(path,root_folders,yr,mnth)

But this has certain limitation as the nested folders increase the scalability will be a problem. So is there any solution that this can be achieved using Recursion or any other method

Solution

You can use recursion to create the folders, passing the folder creation function a running path at each call:

import os
def create_folders(root, *args):
  if args:
    for i in args[0]:
      os.mkdir(p:=os.path.join(root, i))
      create_folders(p, *args[1:])

root_folders = ['f1','f2','f3']
yr = ['2018', '2019']
mnth = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
create_folders(os.getcwd(), root_folders, yr, mnth)

Answered By – Ajax1234

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

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