将多个文件夹里的图片提取到同一文件夹下python代码

问题描述:

这个程序是我在准备深度学习训练时整理数据集用到的。

我现在有一个文件夹rongchi-20240821,里面有101个子文件夹layer1、layer2.。。layer101,

 

 每个子文件夹里有两个文件夹,Data和Figure,

Figure文件夹里有两张图片,比如下图中的1color.bmp和1gray.bmp(文件名数字与上上级文件夹数字对应),

我现在想写一段python代码,能把这些图片提取到一个新的文件夹里,我应该怎么写这个代码? 

 

代码:

import os
import shutil

# 设置源文件夹和目标文件夹
source_folder = 'F:\\dataset\\20240903\\rongchi-20240821'
destination_folder = 'F:\\dataset\\20240903\\rongchi_Combine'

# 创建目标文件夹(如果不存在)
os.makedirs(destination_folder, exist_ok=True)

# 遍历每个子文件夹
for i in range(1, 102):  # 从1到101
    layer_folder = f'layer{i}'
    layer_path = os.path.join(source_folder, layer_folder)

    # 检查子文件夹是否存在
    if os.path.exists(layer_path):
        figure_folder = os.path.join(layer_path, 'Figure')

        # 检查Figure文件夹是否存在
        if os.path.exists(figure_folder):
            # 定义要复制的图片文件路径
            color_image = os.path.join(figure_folder, f'{i}color.bmp')
            gray_image = os.path.join(figure_folder, f'{i}gray.bmp')

            # 复制文件到目标文件夹
            if os.path.exists(color_image):
                shutil.copy(color_image, destination_folder)
            if os.path.exists(gray_image):
                shutil.copy(gray_image, destination_folder)

print("图片提取完成!")

运行之后我们可以得到:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值