Python实现:将特定子文件夹中正负患者数据分类复制到新文件夹
基于Python实现患者正负数据分类复制方案

实现思路
通过os.walk遍历所有层级的文件夹,识别包含Positive/Negative的子目录,将其中的图片文件复制到指定的目标文件夹中。
完整代码实现
import os import shutil # 配置路径:替换为你的源文件夹根路径 source_root = "你的患者文件夹根目录路径" # 目标文件夹路径 positive_target = "./Positive_Img_folder" negative_target = "./Negative_Img_folder" # 创建目标文件夹(不存在则创建) os.makedirs(positive_target, exist_ok=True) os.makedirs(negative_target, exist_ok=True) # 定义需要筛选的图片后缀(可根据实际情况调整) image_extensions = ('.png', '.jpg', '.jpeg', '.bmp') # 遍历所有文件夹 for root, dirs, files in os.walk(source_root): # 判断当前目录是否为Positive或Negative文件夹 if "Positive" in root: target_dir = positive_target elif "Negative" in root: target_dir = negative_target else: continue # 非目标分类文件夹,跳过 # 遍历当前目录下的所有图片文件 for file in files: if file.lower().endswith(image_extensions): # 构建源文件路径和目标文件路径 source_path = os.path.join(root, file) target_path = os.path.join(target_dir, file) # 处理文件名重复的情况:如果目标已存在,添加后缀避免覆盖 counter = 1 while os.path.exists(target_path): name, ext = os.path.splitext(file) target_path = os.path.join(target_dir, f"{name}_{counter}{ext}") counter += 1 # 复制文件 shutil.copy2(source_path, target_path) print(f"已复制: {source_path} -> {target_path}") print("数据分类复制完成!")
关键说明
- 替换
source_root为你的患者文件夹根目录的实际路径 image_extensions可根据你实际的图片格式调整- 代码会自动处理文件名重复的情况,避免覆盖已有文件
- 使用
shutil.copy2而非copy,可以保留文件的元数据(如创建时间)
内容的提问来源于stack exchange,提问作者Asker
相关产品推荐
相关产品推荐

