Reputation: 649
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!
Upvotes: 0
Views: 462
Reputation: 6162
According to documentation makedirs is recursive directory creation function what means it creates a full path you pass to it. So instead of making loops for sub-folders you can just create a list of all path's you need and pass them to os.makedirs one by one e.g.:
folders = ['/user_data/TEST/Project_Files/scene', '/user_data/TEST/Project_Files/assets', '/user_data/TEST/Project_Files/renders', '/user_data/TEST/Project_Files/textures']
for path in folders:
os.makedirs(path)
Upvotes: 1
Reputation: 42758
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'])
Upvotes: 1