Home > OS >  Python Function that take n number of arguments as list and create folder and sub folders based on t
Python Function that take n number of arguments as list and create folder and sub folders based on t

Time:01-24

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

CodePudding user response:

Not sure if this is what you wanted, but I whipped up a short function for you which uses recursion to create a folderstructure from a dictionary:

def folder(root, folderdict, subdir=""):
"""
The folderdict could look something like this:
folderdict = {folder1: None, folder2: None, folder3:{subfolder1: None, subfolder2: {subsubfolder1}}}
"""
# set up path progression for recursion
current_directory = os.path.join(root, subdir)

for foldername, subfolders in folderdict.items():
    path = os.path.join(current_directory, foldername)

    if not os.path.exists(path):
        os.mkdir(path)

    # check if newly created path should contain subfolders
    # if so: start recursion
    if subfolders is not None:
        new_subdir = os.path.join(subdir, foldername)
        folder(root, subfolders, new_subdir)

Be careful though. Recursion usually doesn't scale very well.

CodePudding user response:

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)
  •  Tags:  
  • Related