首页 > 解决方案 > Python查找最近的文件很慢

问题描述

我是在做错什么,还是在应该相当慢的文件路径位置找到最新的文件?

下面的代码需要 3 分钟以上。这是否可以通过约 850 个文件的列表进行解析?

我正在使用正则表达式模式仅查找 .txt 文件,因此在通过我的文件共享位置进行搜索后,它会返回约 850 个文件的列表。这是它解析通过 key=os.path.getctime 获取 max(File) 的列表,我尝试使用 sort 而不是 max 并仅获取顶部文件,但这并没有更快。

import os
import glob

path='C:\Desktop\Test'
fileRegex='*.*txt'
latestFile = get_latest_file(filePath, fileRegex)

def get_latest_file(path,fileRegex):
    fullpath = os.path.join(path, fileRegex)
    list_of_files = glob.iglob(fullpath, recursive=True)

    if not list_of_files:               
        latestFile=''   

    latestFile = max(list_of_files, key=os.path.getctime)
    return latestFile

标签: pythonoperating-systemmax

解决方案


尝试使用os.scandir(),这大大加快了我的文件搜索速度。


推荐阅读