Home > Mobile >  How to create multiple folders inside a directory?
How to create multiple folders inside a directory?

Time:11-17

I been working on a Illustrator bot using mostly pyautogui. Recently I discovered that I can create directories using the os module; this is way easier than automating the same process using pyautogui.

My code:

import os

name = str(input("Template Name: "))

def folders_creation():
    templates_path = "D:/JoyTemplates Remastered/Templates"
    os.makedirs(templates_path   "/"   name   "/Etsy Files")
    os.mkdir(templates_path   "/"   name   "/Editing Files")

My code creates a folder with the name that the user inputs; inside templates_path, after this creates two other folders inside name.

I want to know if there's a different way to create multiple folders inside the same path instead of using mkdir for each extra folder.

CodePudding user response:

You can't create multiple folders using os.makedirs(). You can however use list comprehension to do it neatly.

import os

templates_path = "D:/JoyTemplates Remastered/Templates"

name = str(input("Template Name: "))

# Creating your directories
folder_names = ["Etsy Files", "Editing Files"]
[os.makedirs(os.path.join(templates_path, name, folder)) for folder in folder_names]

As a side note, use os.path.join() to join paths,

CodePudding user response:

You could do something like this:

def folders_creation():
    templates_path = "D:/JoyTemplates Remastered/Templates"
    # create the root folder you need
    os.makedirs(templates_path)
    # create multiple subdirs
    for subdir in ['Etsy Files', 'Editing Files']:
        os.mkdir(f'{templates_path}/{subdir}')

(edit: some copy paste errors, thanks @jezza_99)

  • Related