问题描述:
这个程序是我在准备深度学习训练时整理数据集用到的。
我现在有一个文件夹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("图片提取完成!")
运行之后我们可以得到: