Reputation: 467
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 ten folders
How can I solve this using Python ?
Upvotes: 1
Views: 7684
Reputation: 1438
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))
Upvotes: 2
Reputation: 1071
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 ))
Upvotes: 4
Reputation: 18106
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)
Upvotes: 1
Reputation: 817
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')
Upvotes: 1