【问题标题】:Loop through folders and create new subfolders for each then move images in Python遍历文件夹并为每个文件夹创建新的子文件夹,然后在 Python 中移动图像
【发布时间】:2020-09-17 08:47:13
【问题描述】:

假设我有一个文件夹,其中包含子文件夹 project1, project2, project3, ...

在每个项目中,我都有固定命名为processprogresssession的子文件夹,在这些子文件夹中,还有其他子文件夹和图像文件。

现在我想为每个project 创建子文件夹files1 以移动process 中的所有图像,并创建files2 以移动progresssession 中的所有图像。

请注意,每个项目的图片名称都是唯一的,因此我们忽略了图片名称重复问题。

为了为project1 创建files1,我使用:

import os
dirs = './project1/files1'

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

但我需要遍历所有项目文件夹。

我们如何在 Python 中做到这一点?真诚的感谢。

【问题讨论】:

    标签: python-3.x loops directory shutil mkdirs


    【解决方案1】:

    为每个project 创建file1file2

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

    【讨论】: