Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating/making directories in python (complex)

I am trying to create a bunch of directories/subdirectories that I can copy files into. I am working with Python and I can't seem to find a good way to do this. I have a main path that I will branch off of. Then after that, I have Weights and No_Weights. Male and Female following. Within each of Male and Female folders, I have each ethnicity (Caucasian, African-American, Asian, Hispanic, Indo, Other, Unknown). Within each of those folders, I have age ranges from Below 20, all the way to 70+ (B20, 20, 30, 40, 50, 60, 70).

I have tried to generate all of the paths so all I would have to call is mkdir about 50 times, but that is about 150 lines of code (almost).

Is there any simple way to create all of these folders without having to do it by hand?

like image 571
Brandon Avatar asked Nov 28 '22 19:11

Brandon


1 Answers

import itertools
import os

dirs = [["Weights", "No_Weights"],
        ["Male", "Female"],
        ["Caucasian", "African-American", "Asian", "Hispanic", "Indo", "Other", "Unknown"], 
        ["B20", "20", "30", "40", "50", "60", "70"]]

for item in itertools.product(*dirs):
    os.makedirs(os.path.join(*item))

itertools.product() will construct all possible path variations, then os.path.join() will join the subpaths together using the correct syntax for your platform.

EDIT: os.makedirs() is needed instead of os.mkdir(). Only the former will construct all the intermediate subdirectories in a full path.

like image 117
Tim Pietzcker Avatar answered Dec 04 '22 10:12

Tim Pietzcker