Python提取指定路径下的所有图片到指定路径并删除空文件夹

使用Python的osshutil模块来遍历目录,检查文件,复制图片,并删除空文件夹。下面是一个基本的脚本,该脚本将执行你描述的操作:

import os
import shutil
from collections import defaultdict

def copy_images_and_remove_empty_dirs(src_dir, dst_dir, image_extensions):
    # 确保目标目录存在
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)

    # 映射原始文件名到带序号的文件名
    name_to_counter = defaultdict(int)

    # 遍历源目录
    for root, dirs, files in os.walk(src_dir, topdown=False):
        # 遍历文件
        for file in files:
            # 检查文件扩展名是否为图片
            if file.lower().endswith(image_extensions):
                # 构建源图片路径
                src_file = os.path.join(root, file)

                # 为避免重名,添加序号
                base, ext = os.path.splitext(file)
                counter = name_to_counter[base]
                name_to_counter[base] += 1
                if counter > 0:
                    new_file = f"{base}_{counter}{ext}"
                else:
                    new_file = file

                # 构建目标图片路径
                dst_file = os.path.join(dst_dir, new_file)

                # 复制图片
                shutil.copy2(src_file, dst_file)

        # 遍历子目录,并删除空目录(在遍历文件之后,因为我们要先处理文件)
        for dir in dirs:
            dir_path = os.path.join(root, dir)
            # 检查目录是否为空
            if not os.listdir(dir_path):
                # 移除空目录
                shutil.rmtree(dir_path)

# 示例用法
source_directory = '/path/to/source/directory'
destination_directory = '/path/to/destination/directory'
image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp')  # 你可以根据需要添加更多扩展名

copy_images_and_remove_empty_dirs(source_directory, destination_directory, image_extensions)

请注意:

  • os.walk(src_dir, topdown=False) 使用 topdown=False 是为了确保在处理文件之前先遍历到最底层的目录,这样在删除空目录时不会因为子目录的删除而影响到父目录的遍历。
  • shutil.copy2() 用来复制文件,它还会尝试复制文件的元数据(如时间戳)。
  • defaultdict(int) 用来存储每个图片基本名称(不含扩展名)的计数器,以确保重名时添加序号。
  • shutil.rmtree() 用来删除空目录。
  • 脚本中的 image_extensions 是一个元组,包含了你想要处理的图片文件的扩展名。你可以根据需要添加或删除扩展名。

运行此脚本前,请确保将 source_directorydestination_directory 替换为实际的源目录和目标目录路径。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值