Reputation: 73
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?
Upvotes: 7
Views: 35099
Reputation: 8576
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)
Upvotes: 16
Reputation: 1125
You can loop using a list comprehension, create the directory at each iteration using os.mkdir
and assigning it a name that is the result of joining the base path to a given directory name.
import os
[os.mkdir(os.path.join("/folder", "subdir{}".format(i))) for i in range(100)]
Upvotes: 2
Reputation: 20336
You can't do it in one call like that. Just put one call after another:
os.makedirs("folder/subfolder1")
os.makedir("folder/subfolder2")
Upvotes: 2