利用python遍历文件夹图片并复制保存

本文介绍了一款用于筛选并复制特定图片的Python脚本。该脚本能够遍历指定文件夹下的所有图片,根据预设条件筛选出目标图片,并将它们复制到新的文件夹中。适用于数据集整理等场景。

由于做数据分析老是要筛选相应图片进行训练,于是写下这段代码,遍历文件夹下所有图片,根据需求筛选想要的图片复制到新文件夹

import os
import shutil

IMG_EXTENSIONS = [
    '.jpg', '.JPG', '.jpeg', '.JPEG',
    '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
    '.tif', '.TIF', '.tiff', '.TIFF',
]


def is_image_file(filename):
    return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)


# file_path = os.sep.join(['D:', 'picture', 'hqyy'])
root_path = r"D:\picture\hqyy"
target = '1'
for root, dirs, files in os.walk(root_path):
    '''root 表示当前正在访问的文件夹路径
        dirs 表示该文件夹下的子目录名list
        files 表示该文件夹下的文件list'''
    for file in files:
        file_path = os.path.join(root, file)
        if is_image_file(file_path):
            if file_path.split('\\')[-2] == target:
                if not os.path.exists(root_path + os.sep + target):
                    os.mkdir(root_path + os.sep + target)
                shutil.copy2(file_path, os.path.join(root_path + os.sep + target, file))
                print(file_path)


import os
import shutil
import re

IMG_EXTENSIONS = [
    '.jpg', '.JPG', '.jpeg', '.JPEG',
    '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
    '.tif', '.TIF', '.tiff', '.TIFF',
]


def is_image_file(filename):
    return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)


# file_path = os.sep.join(['D:', 'picture', 'hqyy'])
root_path = r"D:\picture\终RVO"
target_path = r'D:\picture'
for root, dirs, files in os.walk(root_path):
    '''root 表示当前正在访问的文件夹路径
        dirs 表示该文件夹下的子目录名list
        files 表示该文件夹下的文件list'''
    for file in files:
        file_path = os.path.join(root, file)
        if is_image_file(file_path):
            target = re.findall(r'-(\d).', file)
            if target:
                target = target[0]
                if not os.path.exists(target_path + os.sep + target):
                    os.mkdir(target_path + os.sep + target)
                file_name = file_path.split(os.sep)[-3]+'-'+file_path.split(os.sep)[-2]+'.jpeg'
                shutil.copy2(file_path, os.path.join(target_path + os.sep + target, file_name))
                print(file_path)
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值