python 条件批量复制文件

前言

我有一个多级文件夹,我想复制文件夹中除了*.bin文件外的所有文件和*best*.bin文件。

代码

import os
import shutil


def condition_copy(source_path: str, target_path: str, condition):
    """
    条件复制
    :param source_path: 源路径
    :param target_path: 目标路径
    :param condition: 条件函数, 输入完整文件路径, 返回True or False
    :return: None
    """
    paths = []  # 存放文件夹路径
    files = []  # 存放文件路径

    def findfiles(path):
        # 首先遍历当前目录所有文件及文件夹
        file_list = os.listdir(path)
        # 循环判断每个元素是否是文件夹还是文件,是文件夹的话,递归
        for file in file_list:
            # 利用os.path.join()方法取得路径全名,并存入cur_path变量,否则每次只能遍历一层目录
            cur_path = os.path.join(path, file)
            # 判断是否是文件夹
            if os.path.isdir(cur_path):
                paths.append(cur_path)
                findfiles(cur_path)
            else:
                files.append(cur_path)

    findfiles(source_path)
    # 选择所需的文件
    select_files = [i for i in files if condition(i)]

    # 原始路径转换为目标路径
    target_files = [i.replace(source_path, target_path) for i in select_files]
    target_paths = [i.replace(source_path, target_path) for i in paths]

    # 创建文件夹
    if not os.path.exists(target_path):
        os.mkdir(target_path)
    for path in target_paths:
        if not os.path.exists(path):
            os.mkdir(path)

    # 复制文件
    for i in range(len(select_files)):
        if os.path.exists(target_files[i]):  # 跳过已存在的文件
            continue
        shutil.copy2(select_files[i], target_files[i])
        print('(%i/%i)' % (i+1, len(select_files)), target_files[i])

    print('Done!')


def condition(path: str):
    return 'best' in path or (not path.endswith('.bin'))


if __name__ == '__main__':
    source_path = '~/project'
    target_path = '~/project_select'
    condition_copy(source_path, target_path, condition)

注意事项

condition方法定义了文件筛选条件,当一个文件的文件名符合我们的要求时返回True,否则返回False

def condition(path: str):
    return 'best' in path or (not path.endswith('.bin'))

source_pathtarget_path形式要一样,切勿在其中一个后面加/

# 正确1
source_path = '~/project'
target_path = '~/project_select'
# 正确2
source_path = '~/project/'
target_path = '~/project_select/'
# 错误示范
source_path = '~/project/'
target_path = '~/project_select'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值