Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - create folder with multiple subfolders

I need to create a list of folders each with multiple subfolders that are not nested. I have used

os.makedirs('folder/subfolder')

to create a folder and a subfolder but I can only make multiple nested folders work:

os.makedirs('folder/subfolder1/subfolder2/subfolder3')

where sub3 is nested in sub2 which is nested in sub1. What I want is for sub 1, 2 and 3 all to be nested in 'folder' together (3 folders inside 1 folder). I tried

os.makedirs('folder/(subfolder1, subfolder2)')

but that just creates a folder titled "(subfolder1, subfolder2)" Does anyone know the correct syntax for this? Is it even possible with the makedirs function?

like image 651
jredd Avatar asked Mar 11 '16 21:03

jredd


1 Answers

Use a loop:

for i in range(1,100):
    os.makedirs(os.path.join('folder', 'subfolder' + str(i)))

Or, if you have the names in a list:

subfolder_names = []
for subfolder_name in subfolder_names:
    os.makedirs(os.path.join('folder', subfolder_name))

p.s.

In case to ignore already-exist folder

os.makedirs('/path/to/dir', exist_ok=True)
like image 137
Anmol Singh Jaggi Avatar answered Sep 30 '22 18:09

Anmol Singh Jaggi