亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python實現(xiàn)遍歷包含大量文件的文件夾

 更新時間:2023年04月13日 10:36:46   作者:SpikeKing  
在處理大模型的訓(xùn)練數(shù)據(jù)時,經(jīng)常需要遍歷大型文件夾,其中,可能包括數(shù)千萬或數(shù)億個文件,所以本文為大家整理了Python遍歷包含大量文件的文件夾的方法,希望對大家有所幫助

在處理大模型的訓(xùn)練數(shù)據(jù)時,經(jīng)常需要遍歷大型文件夾,其中,可能包括數(shù)千萬或數(shù)億個文件,這時,一般的Python遍歷函數(shù)就會非常慢,例如os.walk、glob、path.rglob等等,同時,無法預(yù)估整體的遍歷時間。

本文,通過Python的os.scandir,基于廣度優(yōu)先搜索算法,實現(xiàn)可控、高效的遍歷文件,同時,輸出遍歷日志,支持后綴篩選,去除隱藏文件,實現(xiàn)遍歷包含大量文件的文件夾的功能。

os.scandir 是一個目錄迭代函數(shù),返回 os.DirEntry 對象的迭代器,對應(yīng)于由 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:  # 根據(jù)后綴名搜索
                    if path.endswith(ext):
                        paths_list.append(path)
                else:
                    paths_list.append(path)
    return paths_list

輸出日志:

[Info] 初始化路徑開始!
[Info] 數(shù)據(jù)集路徑: /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:  # 根據(jù)后綴名搜索
                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:  # 根據(jù)后綴名搜索
            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

到此這篇關(guān)于Python實現(xiàn)遍歷包含大量文件的文件夾的文章就介紹到這了,更多相關(guān)Python遍歷文件夾內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Django中Cookie設(shè)置及跨域問題處理詳解

    Django中Cookie設(shè)置及跨域問題處理詳解

    本文主要介紹了Django中Cookie設(shè)置及跨域問題處理,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • Python BeautifulSoup中文亂碼問題的2種解決方法

    Python BeautifulSoup中文亂碼問題的2種解決方法

    這篇文章主要介紹了Python BeautifulSoup中文亂碼問題的2種解決方法,需要的朋友可以參考下
    2014-04-04
  • vscode調(diào)試django項目的方法

    vscode調(diào)試django項目的方法

    這篇文章主要介紹了vscode調(diào)試django項目的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • python實現(xiàn)不同數(shù)據(jù)庫間數(shù)據(jù)同步功能

    python實現(xiàn)不同數(shù)據(jù)庫間數(shù)據(jù)同步功能

    這篇文章主要介紹了python實現(xiàn)不同數(shù)據(jù)庫間數(shù)據(jù)同步功能,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-02-02
  • 重溫Python基礎(chǔ)之列表操作

    重溫Python基礎(chǔ)之列表操作

    這篇文章主要帶大家來復(fù)習(xí)一下Python基礎(chǔ)中的列表操作,不知道各位還記得多少呢?文中的示例代碼講解詳細,對我們學(xué)習(xí)Python有一定幫助,需要的可以參考一下
    2022-11-11
  • Python基礎(chǔ)入門之魔法方法與異常處理

    Python基礎(chǔ)入門之魔法方法與異常處理

    在python中,所有以“__"雙下劃線包起來的方法,都統(tǒng)稱為魔法方法,下面這篇文章主要給大家介紹了關(guān)于Python基礎(chǔ)入門之魔法方法與異常處理的相關(guān)資料,需要的朋友可以參考下
    2021-11-11
  • python修改操作系統(tǒng)時間的方法

    python修改操作系統(tǒng)時間的方法

    這篇文章主要介紹了python修改操作系統(tǒng)時間的方法,涉及Python同步網(wǎng)絡(luò)時間與本機時間的相關(guān)技巧,需要的朋友可以參考下
    2015-05-05
  • Django中間件攔截未登錄url實例詳解

    Django中間件攔截未登錄url實例詳解

    在本篇文章里小編給各位整理了關(guān)于Django中間件攔截未登錄url的實例內(nèi)容以及相關(guān)知識點,有需要的朋友們可以學(xué)習(xí)下。
    2019-09-09
  • Pycharm github配置實現(xiàn)過程圖解

    Pycharm github配置實現(xiàn)過程圖解

    這篇文章主要介紹了Pycharm github配置實現(xiàn)過程圖解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-10-10
  • python中reshape函數(shù)用法示例詳解

    python中reshape函數(shù)用法示例詳解

    reshape函數(shù)是Numpy庫中的一個函數(shù),可以用于改變一個數(shù)組的形狀,例如將一個二維數(shù)組轉(zhuǎn)換成一個三維數(shù)組,這篇文章主要介紹了python中reshape函數(shù)用法詳解,需要的朋友可以參考下
    2023-09-09

最新評論