user5778614 user5778614 - 5 months ago 15
Python Question

How to makedirs from a list and include a list of subdirectories in python?

Made directories from a list using this:

import os

cwd = os.getcwd()
folders = ['file1','file2','file3']
for folder in folders:
os.mkdir(os.path.join(cwd,folder))


Would also like to add three subdirectories within each of those files, e.g ['sub1','sub2','sub3']

Tried something like this (and other simple-minded approaches) with no success:

import os

cwd = os.getcwd()
folders = ['file1','file2','file3']
subfolders = ['sub1','sub2','sub3']
for folder in folders:
os.makedirs('os.path.join(cwd,folder/subfolders/)')


Any ideas? Thank you!

Answer
import os

cwd = os.getcwd()
folders = ['file1','file2','file3']
subfolders = ['sub1','sub2','sub3']

for folder in folders:
    os.mkdir(os.path.join(cwd, folder))

    # Create sub-folders.
    for sub in subfolders:
        os.mkdir(os.path.join(cwd, folder, sub))
Comments