1

If I have a folder test which has multiple subfolders A, B, C, etc., each has same structure sub1, sub2 and sub3:

├─A
│  ├─sub1
│  ├─sub2
│  └─sub3
├─B
│  ├─sub1
│  ├─sub2
│  └─sub3
└─C
|   ├─sub1
|   ├─sub2
|   └─sub3
...

I want to create subfolders named a and b only in sub1 and sub2 and ignore other subfolders (sub3...). This is expected result:

├─A
│  ├─sub1|--a
│  |     |--b
│  ├─sub2|--a
│  |     |--b
│  └─sub3
├─B
│  ├─sub1|--a
│  |     |--b
│  ├─sub2|--a
│  |     |--b
│  └─sub3
└─C
│  ├─sub1|--a
│  |     |--b
│  ├─sub2|--a
│  |     |--b
   └─sub3
...

I can create folders a and b with code below, but I don't how can I do this sub1 and sub2? Thanks.

import os

root_path =r"D:\test"
sub_folders = ['a', 'b']
folders = []
for path in os.listdir(root_path):
   folders.append(os.path.join(root_path, path))

for f in folders:
    os.chdir(f)
    for sub_folder in sub_folders:
        os.mkdir(sub_folder)

Update: the code below doesn't create subfolders a and b:

sub_folders = ['a', 'b']
folders = []

for path in os.listdir(root_path):
    if path in ('sub1', 'sub2'):
        folders.append(os.path.join(root_path, path))

for f in folders:
    os.chdir(f)
    for sub_folder in sub_folders:
        os.mkdir(sub_folder)

UPDATE: the code below works, thanks to @Baltschun Ali.

import os

path = 'C:/Users/User/Desktop/test1'
def create_sub_folder (*arg):
    if len(arg) < 3:
        for i in arg[0]:
            for j in arg[1]:
                path = i+"/"+j
                if os.path.exists(path) is False:
                    os.makedirs(path)
    else:      
        arg1 = [i+"/"+j for i in arg[0] for j in arg[1]]
        create_sub_folder(arg1,*(i for i in arg[2:]))

for dir in os.listdir(path):
    if os.path.isdir(os.path.join(path, dir)):
        print(dir)
        create_sub_folder([dir], ['sub1', 'sub2'],['a','b'])

3 Answers 3

1

more dynamic.

EDITED CODE

def create_sub_folder (*arg):
    if len(arg) < 3:
        for i in arg[0]:
            for j in arg[1]:
                path = i+"/"+j
                if os.path.exists(path) is False:
                    os.makedirs(path)
    else:      
        arg1 = [i+"/"+j for i in arg[0] for j in arg[1]]
        create_sub_folder(arg1,*(i for i in arg[2:]))

CALL METHOD

create_sub_folder(['A','B'],['sub1','sub2'],['a','b'])

RESULT :

before

enter image description here

after

enter image description here

you can pass more than 3 levels of subfolder just pass more array in arg

create_sub_folder([],[],[],[],[],[],['a','b'])
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your help. Sorry maybe I was not clear, in fact I already have a folder structure (not need to create "D:\test" but your code is useful to create test data), I just want to create subfolders a, b under sub1 and sub2, not sub1--a, sub1--b, or sub2--a, sub2--b.
sorry, i miss your first question (before you edit it)
Thanks, is there a method to avoid to list ['A','B'], because I have handreds of folders at this level in real data?
do you mean, add a subfolder to all parent folder? just get all your parent folder using glob and pass it into first array of arg create_sub_folder(array_folder_from_glob,['sub1','sub2'],['a','b'])
1

You can use an if statement in the first for loop to avoid adding the path to the list only if it is one of sub1 and sub2:

for path in os.listdir(root_path):
   if path in ('sub1', 'sub2'):
       folders.append(os.path.join(root_path, path))

1 Comment

Thanks, I replace your code but it doesn't work out. Please check update of my question.
1

You can use the glob library:

import glob, os

for new_dir_name in ('a','b'):
    for subn in ('sub1', 'sub2'):
        for sub_folder in glob.glob(os.path.join('*',subn), recursive=True):
            os.mkdir(os.path.join(sub_folder, new_dir_name))

Tested in Linux:

$ mkdir -p {A,B}/sub1 {A,B,C}/sub2 
$ python make_sub_dirs.py # run the python script above
$ ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'

Results:

   |-A
   |---sub1
   |-----a
   |-----b
   |---sub2
   |-----a
   |-----b
   |-B
   |---sub1
   |-----a
   |-----b
   |---sub2
   |-----a
   |-----b
   |-C
   |---sub2
   |-----a
   |-----b
   |-ipp2
   |---log

5 Comments

Thanks for your help, but I hope to create a and b for both sub1 and sub2.
Sorry that I miss this point. Will correct the answer in a moment.
I think maybe we should use os.walk, no?
@ahbon That will also work. But glob has the nice feature of "wildcard" expansion so that we don't need to handle the path-pattern matching in our code.
I try with your method, it didn't create a and b, did you make folders successfully?

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.