python-3.xloopsdirectoryshutilmkdirs

Loop through folders and create new subfolders for each then move images in Python


Let's say I have a folder which has subfolders project1, project2, project3, ... in it.

enter image description here

In each of project, I have subfolders fixedly named process, progress and session in it, inside those subfolders, there are also other subfolders and image files.

Now I want to create subfolders files1 for each project to move all the images from process, and create files2 to move all the images from progress and session.

Please note the names of images for each projects are unique, so we ignore image name duplicates issues.

For creating files1 for project1, I use:

import os
dirs = './project1/files1'

if not os.path.exists(dirs):
    os.makedirs(dirs)

But I need to loop through all the projects folders.

How could we do that in Python? Sincere thanks.


Solution

  • For create file1 and file2 for each project:

    # Remove non-images files
    base_dir = './'
    for root, dirs, files in os.walk(base_dir):
        for file in files:
            # print(file)
            pic_path = os.path.join(root, file)
            ext = os.path.splitext(pic_path)[1].lower()
            if ext not in ['.jpg', '.png', '.jpeg']:
                os.remove(pic_path)
                print(pic_path)
    
    # create files1 and files2
    for child in os.listdir(base_dir):
        child_path = os.path.join(base_dir, child)
        os.makedirs(child_path + '/file1', exist_ok=True)
        os.makedirs(child_path + '/file2', exist_ok=True)