Search code examples
pythondirectorymkdir

Batch creation of folders


I am trying to script a function in which it will creates a list of folders and sub-folders.

While my code is as follows, I was wondering if there are any better methods for me to create the sub-folders? (See createFolders function line 5 onwards)

Not that the naming of the sub-folders will be changed but currently I am hard-coding it which can be a pain if I have to create more main/sub-folders...

import os

directory = '/user_data/TEST'

def createFolders():
    mainItems = ['Project_Files', 'Reference', 'Images']
    for mainItem in mainItems:
        os.makedirs(directory + '/' + str(mainItem))

    projDir = directory + '/' + str(mainItems[0])
    projItems = ['scene', 'assets', 'renders', 'textures']
    for projItem in projItems:
        os.makedirs(projDir + '/' + str(projItem))

if not os.path.exists(directory):
    print '>>> Creating TEST directory'
    os.makedirs(directory)
else:
    print '>>> TEST exists!'

createFolders()

Any advice is appreciated!


Solution

  • You should use os.path.join to concatenate paths. str is unnecessary. You can use nested lists, to define the structure of subfolders:

    import os
    
    directory = '/user_data/TEST'
    
    def create_folders(basedir, subfolders):
        for subfolder in subfolders:
            if isinstance(subfolder, (list, tuple)):
                create_folders(os.path.join(basedir, subfolder[0]), subfolder[1])
            else:
                os.makedirs(os.path.join(basedir, subfolder))
    
    create_folders(directory, [
        ('Project_Files', ['scene', 'assets', 'renders', 'textures']),
        'Reference', 'Images'])