1

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 ?

1
  • Use 2 for loops and os.path.join. Commented Jul 17, 2017 at 9:58

4 Answers 4

4
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 ))
Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

1

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')

Comments

1

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)

1 Comment

It will create N folder nested in M, it's not what he want

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.