• 技术文章 >后端开发 >Python教程

    如何使用Python遍历一个包含大量文件的文件夹?

    WBOYWBOY2023-04-25 15:22:08转载54

    在处理大模型的训练数据时,经常需要遍历大型文件夹,其中,可能包括数千万或数亿个文件,这时,一般的Python遍历函数就会非常慢,例如os.walk、glob、path.rglob等等,同时,无法预估整体的遍历时间。

    Python怎么实现遍历包含大量文件的文件夹

    本文,通过Python的os.scandir,基于广度优先搜索算法,实现可控、高效的遍历文件,同时,输出遍历日志,支持后缀筛选,去除隐藏文件,实现遍历包含大量文件的文件夹的功能。

    os.scandir 是一个目录迭代函数,返回 os.DirEntry 对象的迭代器,对应于由 path 指定目录中的条目,这些条目以任意顺序生成,不包括特殊条目 ‘.’ 和 ‘…’。os.scandir 的运行效率要高于 os.walk,在 PEP 471 中,Python 官方也推荐使用 os.scandir 遍历目录 。

    源码

    def traverse_dir_files_for_large(root_dir, ext=""):
        """
        列出文件夹中的文件, 深度遍历
        :param root_dir: 根目录
        :param ext: 后缀名
        :return: 文件路径列表
        """
        paths_list = []
        dir_list = list()
        dir_list.append(root_dir)
        while len(dir_list) != 0:
            dir_path = dir_list.pop(0)
            dir_name = os.path.basename(dir_path)
            for i in tqdm(os.scandir(dir_path), f"[Info] dir {dir_name}"):
                path = i.path
                if path.startswith('.'):  # 去除隐藏文件
                    continue
                if os.path.isdir(path):
                    dir_list.append(path)
                else:
                    if ext:  # 根据后缀名搜索
                        if path.endswith(ext):
                            paths_list.append(path)
                    else:
                        paths_list.append(path)
        return paths_list

    输出日志:

    [Info] 初始化路径开始!
    [Info] 数据集路径: /alphafoldDB/pdb_from_uniprot
    [Info] dir pdb_from_uniprot: 256it [00:10, 24.47it/s]
    [Info] dir 00: 240753it [00:30, 7808.36it/s]
    [Info] dir 01: 241432it [00:24, 9975.56it/s]
    [Info] dir 02: 240466it [00:24, 9809.68it/s]
    [Info] dir 03: 241236it [00:22, 10936.76it/s]
    [Info] dir 04: 241278it [00:24, 10011.14it/s]
    [Info] dir 05: 241348it [00:25, 9414.16it/s]

    补充

    除了上文的方式,小编还为大家整理了其他Python遍历文件夹的方法,需要的可以参考一下

    方法一:通过os.walk()遍历,直接处理文件即可

    def traverse_dir_files(root_dir, ext=None, is_sorted=True):
        """
        列出文件夹中的文件, 深度遍历
        :param root_dir: 根目录
        :param ext: 后缀名
        :param is_sorted: 是否排序,耗时较长
        :return: [文件路径列表, 文件名称列表]
        """
        names_list = []
        paths_list = []
        for parent, _, fileNames in os.walk(root_dir):
            for name in fileNames:
                if name.startswith('.'):  # 去除隐藏文件
                    continue
                if ext:  # 根据后缀名搜索
                    if name.endswith(tuple(ext)):
                        names_list.append(name)
                        paths_list.append(os.path.join(parent, name))
                else:
                    names_list.append(name)
                    paths_list.append(os.path.join(parent, name))
        if not names_list:  # 文件夹为空
            return paths_list, names_list
        if is_sorted:
            paths_list, names_list = sort_two_list(paths_list, names_list)
        return paths_list, names_list

    方法二:通过pathlib.Path().rglob()遍历,需要过滤出文件,速度较快。注意glob()不支持递归遍历

    def traverse_dir_files(root_dir, ext=None, is_sorted=True):
        """
        列出文件夹中的文件, 深度遍历
        :param root_dir: 根目录
        :param ext: 后缀名
        :param is_sorted: 是否排序,耗时较长
        :return: [文件路径列表, 文件名称列表]
        """
        names_list = []
        paths_list = []
        for path in list(pathlib.Path(root_dir).rglob("*")):
            path = str(path)
            name = path.split("/")[-1]
            if name.startswith('.') or "." not in name:  # 去除隐藏文件
                continue
            if ext:  # 根据后缀名搜索
                if name.endswith(ext):
                    names_list.append(name)
                    paths_list.append(path)
            else:
                names_list.append(name)
                paths_list.append(path)
        if not names_list:  # 文件夹为空
            return paths_list, names_list
        if is_sorted:
            paths_list, names_list = sort_two_list(paths_list, names_list)
        return paths_list, names_list

    以上就是如何使用Python遍历一个包含大量文件的文件夹?的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除
    专题推荐:Python
    上一篇:通过少量代码即可提取大量时间序列特征 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • 使用Python和pywinauto实现自动化采集任务的步骤和方法• Python速查表大全,你掌握了哪些知识点?• Python中如何高效地实现列转行操作• python怎么使用pyshp读写shp文件• Python中异常的传递性和手动抛出异常的方法
    1/1

    PHP中文网