Home > Software engineering >  Python: Create subdirectories at the end of the tree
Python: Create subdirectories at the end of the tree

Time:10-06

Please see my directory tree below.

I need to add an Aug 2022 folder at the end of the tree for each of Subfolder1, 2, and 3.

But these subfolder1, 2, 3 have different levels, for example:

The Aug 2022 folder should be nested under subfolder1/subfolder1_level2;

whereas in subfolder2 the Aug 2022 folder is nested under subfolder2_level1;

Lastly, the Aug 2022 is nested under level3 for subfolder3.

Thank you!

\main_folder\subfolder1_level1
\main_folder\subfolder2_level1
\main_folder\subfolder3_level1
\main_folder\subfolder1_level1\subfolder1_level2
\main_folder\subfolder1_level1\subfolder1_level2\Jul 2022
\main_folder\subfolder1_level1\subfolder1_level2\Jun 2022
\main_folder\subfolder2_level1\Jul 2022
\main_folder\subfolder2_level1\Jun 2022
\main_folder\subfolder3_level1\subfolder3_level2
\main_folder\subfolder3_level1\subfolder3_level2\subfolder3_level3
\main_folder\subfolder3_level1\subfolder3_level2\subfolder3_level3\Jul 2022
\main_folder\subfolder3_level1\subfolder3_level2\subfolder3_level3\Jun 2022

CodePudding user response:

This should do it given your directory structure and assuming there is already a Jul 2022 in all the directories you're interested in:

import os

src = r'root_directory'
for root, directories, files in os.walk(src):
    if 'Jul 2022' in directories:
        os.mkdir(os.path.join(root, 'Aug 2022'))
  • Related