1

How do I create a multiple different folders that also contain multiple different folders using python?
My path is: './work/animals/'. The 'animals' directory contains the folders 'cat', 'dog', 'horse', 'mouse', 'lion', 'cheetah', 'rat', 'baboon', 'donkey', 'snake' and 'giraffe'. I have managed to write the part that creates all the animal folders (code below), but I also wanted to create three other subfolders namely 'male', 'female' and 'uncategorized' in all the folders in animals.

import os
root_path = './work/animals/'
folders = ['cat','dog','horse','mouse','lion','cheetah','rat','baboon','donkey','snake','giraffe']

for folder in folders:
     os.mkdir(os.path.join(root_path,folder))
2
  • Can you write out the paths of these directories you want to create? That should point you in the right direction. Commented Apr 8, 2016 at 18:28
  • Did you check stackoverflow.com/questions/14506864/…? Commented Apr 8, 2016 at 18:38

2 Answers 2

1

How about simply doing :

import os
root_path = './work/animals/'
folders = ['cat','dog','horse','mouse','lion','cheetah','rat','baboon','donkey','snake','giraffe']
subfolders = ['male', 'female', 'uncategorized']
for folder in folders:
    os.mkdir(os.path.join(root_path,folder))
    for subfolder in subfolders : 
        os.mkdir(os.path.join(root_path,folder,subfolder))
Sign up to request clarification or add additional context in comments.

Comments

1

You can use itertools.product to get the combinations of animals plus gender that you want and then use os.makedirs which will create intermediate directories for you.

import os
import itertools

root_path = './work/animals/'

folders = ['cat','dog','horse','mouse','lion','cheetah','rat','baboon','donkey','snake','giraffe']
genders = ['male', 'female', 'uncategorized']

for folder,gender in itertools.product(folders, genders):
    os.makedirs(os.path.join(root_path,folder,gender))

Comments

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.