栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python实现条件复制

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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_path和target_path形式要一样,切勿在其中一个后面加/

# 正确1
source_path = '~/project'
target_path = '~/project_select'
# 正确2
source_path = '~/project/'
target_path = '~/project_select/'
# 错误示范
source_path = '~/project/'
target_path = '~/project_select'
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/926332.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号