You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现多层子文件夹照片提取至目标目录?现有代码仅支持第一层

解决深层子文件夹照片提取问题

原代码仅能遍历源文件夹下的第一层子目录,无法处理多层嵌套的子文件夹。要实现深层目录的遍历,推荐使用os.walk()方法,它会自动递归遍历源目录下的所有层级子目录,同时保留原有的目录结构映射到目标文件夹。

修改后的代码

import os
import shutil

# 配置路径和目标文件扩展名
source_dir = r"C:\Users\YourUserName\SourceDirectory"
destination_dir = r"C:\Users\YourUserName\DestinationDirectory"
target_extensions = (".jpg", ".jpeg", ".png")

# 递归遍历源目录下所有层级的文件和文件夹
for root, dirs, files in os.walk(source_dir):
    # 计算当前目录相对于源目录的路径,用于在目标目录重建结构
    relative_path = os.path.relpath(root, source_dir)
    # 构建目标目录的对应路径
    dest_folder = os.path.join(destination_dir, relative_path)
    
    for file in files:
        # 筛选符合扩展名的文件(兼容大小写)
        if file.lower().endswith(target_extensions):
            source_file = os.path.join(root, file)
            dest_file = os.path.join(dest_folder, file)
            
            # 确保目标目录存在
            os.makedirs(dest_folder, exist_ok=True)
            # 复制文件
            shutil.copy(source_file, dest_file)
            print(f"已复制: {source_file} -> {dest_file}")

关键改进点

  • 用os.walk()替代手动遍历:该方法会自动遍历源目录下所有子层级,返回当前根目录、子目录列表、文件列表,无需手动写递归逻辑
  • 保留原目录结构:通过os.path.relpath()计算当前目录相对源目录的路径,在目标目录中重建完全一致的层级结构
  • 大小写兼容:添加file.lower(),确保.JPG、.PNG这类大写扩展名的文件也能被正确筛选

内容的提问来源于stack exchange,提问作者amansour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 08:07:18