Joy
Joy

Reputation: 33

How to create multiple folders inside a directory?

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.

Upvotes: 0

Views: 1040

Answers (2)

Grismar
Grismar

Reputation: 31329

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)

Upvotes: 1

jezza_99
jezza_99

Reputation: 1095

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,

Upvotes: 1

Related Questions