广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python实现遍历包含大量文件的文件夹
  • 935
分享到

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

Python实现遍历文件夹Python遍历文件夹Python文件夹 2023-05-15 17:05:50 935人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

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

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

本文,通过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实现遍历包含大量文件的文件夹的文章就介绍到这了,更多相关Python遍历文件夹内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Python实现遍历包含大量文件的文件夹

本文链接: https://www.lsjlt.com/news/209292.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作