user5778614
user5778614

Reputation: 69

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!

Upvotes: 1

Views: 1507

Answers (2)

lulyon
lulyon

Reputation: 7225

There is no need to create parent directory explicitly, for makedirs automatically create parent folder if not exists. For your solution, A workable concise code snippet as follows:

import os

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

paths = [os.path.join(cwd, folder, sub) for folder in folders for sub in subfolders]

for path in paths:
    os.makedirs(path)

Note that the above code is just a little modification of your secondly-tried code:

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

Upvotes: 0

Nadh
Nadh

Reputation: 7243

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

Upvotes: 3

Related Questions