美文网首页
python3在文件夹中查找指定文件方法封装

python3在文件夹中查找指定文件方法封装

作者: 写给明天的自己 | 来源:发表于2022-01-05 17:20 被阅读0次

不是人人都能活的低调,可以低调的基础是随时都能高调。

上一篇:configobj读写.ini配置文件方法封装
下一篇:python3使用hmac、hashlib加密字符串方法封装

本篇文章介绍一种方法在文件夹中查找指定文件:
1、方法【get_all_file】:根据给出的路径进行递归,找到文件夹下所有的文件,以生成器的方式返回(占用内存低),也可以添加到列表(list)(占用内存高)。
2、方法【expand_list】:递归嵌套列表,展开列表,此步骤根据数据结构,如果自己的文件的地址是多层嵌套的列表,可以使用该方法展开列表。
3、方法【find_file】:查找指定文件。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os


class FolderFindFile:

    PARAM_TYPE_ERR = 'Wrong parameter type.'
    FILE_NOT_FOUND = '系统找不到指定的路径: {}'

    @classmethod
    def get_all_file(cls, dir_path):
        """
        获取一个目录以及该目录下所有子目录的文件,以生成器的方式输出(文件绝对路径)。
        :param dir_path: 需要遍历的目录。
        :type dir_path str

        :return: 以生成器的方式输出
        """

        try:
            files = os.listdir(dir_path)
        except FileNotFoundError:
            return cls.FILE_NOT_FOUND.format(dir_path)
        else:
            for file_name in files:

                file_abs_path = os.path.join(dir_path, file_name)

                # 判断是否是目录
                if os.path.isdir(file_abs_path):
                    for file in FolderFindFile.get_all_file(file_abs_path):

                        yield file

                else:
                    yield file_abs_path

    @staticmethod
    def expand_list(nested_list):
        """
        用递归方法展开多层列表,以生成器方式输出
        :param nested_list: 嵌套列表,如:[12,'qq',[34,'oo',[56],[78]]]
        :return: 以生成器的方式输出
        使用示例:
        nested_list = [12,'qq',[34,'oo',[56],[78]]]
        exp_list = list(FolderFindFile.expand_list(nested_list))
        print(exp_list)
        result:[12, 'qq', 34, 'oo', 56, 78]
        """

        if isinstance(nested_list, list):
            for i in nested_list:
                for element in FolderFindFile.expand_list(i):
                    yield element
        else:
            yield nested_list

    @classmethod
    def find_file(cls, file_list, suffix_list):
        """
        用户查找列表中各个类型的文件,返回该文件。
        :param file_list: 需要查找的文件的列表,eg:['one.txt','two.xls']
        :type file_list list

        :param suffix_list: 查找的文件的后缀名列表,eg:['.txt', '.xls'],必须有点即英文句号【.】
        :type suffix_list list
        :return: list
        """

        if isinstance(file_list, list) and isinstance(suffix_list, list):

            new_list = []
            for i in range(len(file_list)):

                suffix = os.path.splitext(file_list[i])[1]

                if suffix in suffix_list:
                    new_list.append(file_list[i])

            return new_list

        else:

            raise TypeError(cls.PARAM_TYPE_ERR)

以上方法根据自己的需求进行选择使用,有不足的地方,请各位大佬指出。


如果感觉本文对您有帮助可以点个赞哦

本文为学习笔记,转载请标明出处

本文仅供交流学习,请勿用于非法途径

仅是个人意见,如有想法,欢迎留言

相关文章

网友评论

      本文标题:python3在文件夹中查找指定文件方法封装

      本文链接:https://www.haomeiwen.com/subject/yegxgltx.html