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

如何将多级目录下的所有JPG图片批量复制到指定目录?

解决批量复制嵌套目录下图片的问题

我来帮你排查下代码失效的原因,再给你几个可行的解决方案~

你的代码为什么没生效?

核心问题出在路径匹配错误:
你在循环里用了glob.iglob(os.path.join(dirpath, "*.jpg")),这个路径是直接在根目录/Volumes/LaCie/lfw/下找.jpg文件,但你的图片都藏在dirX/littledirX的嵌套目录里,自然找不到任何文件,复制操作也就不会执行。另外你也没有遍历到第二层的littledir目录。

解决方案1:用os.walk递归遍历(最推荐)

os.walk会自动遍历整个目录树,不用手动嵌套多层循环,代码更简洁可靠,还能顺便处理重名文件的问题(毕竟每个子目录都有image1.jpg,直接复制会覆盖):

import os
import shutil

# 原目录和目标目录的路径
source_root = '/Volumes/LaCie/lfw/'
target_dir = '/Volumes/LaCie/lfw/dstn/'

# 确保目标目录存在,不存在则创建(exist_ok=True避免重复创建报错)
os.makedirs(target_dir, exist_ok=True)

# 递归遍历所有目录
for root, _, files in os.walk(source_root):
    # 跳过目标目录本身,防止复制刚移过去的文件
    if root == target_dir:
        continue
    for file in files:
        # 只处理jpg格式的文件(小写后缀兼容大小写)
        if file.lower().endswith('.jpg'):
            # 拼接源文件的完整路径
            src_file = os.path.join(root, file)
            # 生成不重复的文件名:用父目录名(比如dir1)作为前缀,避免重名覆盖
            unique_filename = f"{os.path.basename(os.path.dirname(root))}_{file}"
            # 拼接目标文件路径
            dst_file = os.path.join(target_dir, unique_filename)
            # 复制文件
            shutil.copy(src_file, dst_file)
            # 可选:打印进度,方便跟踪复制情况
            print(f"已复制: {src_file} → {dst_file}")

print(f"所有图片已复制完成,目标目录:{target_dir}")

解决方案2:手动遍历嵌套目录(贴合你的原始思路)

如果你想按照自己最初的循环逻辑修改,只需要修正路径,逐层遍历到littledir目录下找图片:

import os
import glob
import shutil

source_root = '/Volumes/LaCie/lfw/'
target_dir = '/Volumes/LaCie/lfw/dstn/'

os.makedirs(target_dir, exist_ok=True)

# 遍历第一层目录(dir1到dir3000)
for dir_name in os.listdir(source_root):
    dir_full_path = os.path.join(source_root, dir_name)
    # 跳过非目录、.DS_Store和目标目录
    if not os.path.isdir(dir_full_path) or dir_name == 'dstn' or dir_name.endswith('.DS_Store'):
        continue
    # 遍历第二层目录(littledir1到littledir3000)
    for sub_dir_name in os.listdir(dir_full_path):
        sub_dir_full_path = os.path.join(dir_full_path, sub_dir_name)
        if not os.path.isdir(sub_dir_full_path) or sub_dir_name.endswith('.DS_Store'):
            continue
        # 在第二层目录里查找所有jpg文件
        for jpg_file in glob.iglob(os.path.join(sub_dir_full_path, "*.jpg")):
            # 同样处理重名问题
            unique_filename = f"{dir_name}_{os.path.basename(jpg_file)}"
            shutil.copy(jpg_file, os.path.join(target_dir, unique_filename))
            print(f"已复制: {jpg_file} → {os.path.join(target_dir, unique_filename)}")

print(f"复制完成!所有图片都在{target_dir}里")

关键注意事项

  • 重名文件处理:每个子目录都有image1.jpg和image2.jpg,直接复制会导致后面的文件覆盖前面的,所以一定要给文件名加前缀(比如原目录名)来保证唯一性。
  • 目标目录存在性:用os.makedirs(..., exist_ok=True)确保目标目录存在,避免运行时抛出目录不存在的错误。
  • 跳过系统文件:记得过滤.DS_Store这类Mac系统生成的隐藏文件,避免不必要的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:44:12