Skip to content Skip to sidebar Skip to footer

How To Create Multiple Nested Folders In Python?

I have a root folder, say Z. Inside Z, I have to create ten folders (say Q, W, E, R, T, Y, U, I, O, P, A). Further, I would like to make two folders (say M and N) in each of these

Solution 1:

import os
root = 'Z'
midFolders = ['Q', 'W', 'E', 'R', 'T', 'Z', 'U']
endFolders = ['M', 'N']
for midFolder in midFolders:
    for endFolder in endFolders:
        os.makedirs(os.path.join(root, midFolder,endFolder ))

Solution 2:

import os
atuple = ('Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A')
atuple2 = ('M', 'N')
for dir1 in atuple:
    for dir2 in atuple2:
        os.makedirs(os.path.join(dir1, dir2))

Solution 3:

You could have "Permission denied" problem. Use sudo and chmod on the script.

import os  
paths=['Q','W','E','R','T','Y','U','I','O','P','A']
main_path = '/root/'

for p in paths:
   os.mkdir(main_path+p)
   os.mkdir(main_path+p+'/M')
   os.mkdir(main_path+p+'/N')

Solution 4:

os.makedirs, will create all non-existant directories from a path and os.path.join will create a full path from arguments:

import os
root = '/tmp'
directories = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A']
nestedDirectories = ['M', 'N']

for d in directories:
    path = os.path.join(root, d, *nestedDirectories)
    os.makedirs(path)

Post a Comment for "How To Create Multiple Nested Folders In Python?"