You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python查找最新文件速度过慢,遍历850个文件耗时3分钟是否正常?

问题分析与优化方案

耗时异常原因

  • 850个文件检索耗时3分钟属于网络共享路径场景下的典型性能表现,但远高于本地磁盘检索速度,核心瓶颈为:os.path.getctime对每个文件单独发起网络请求拉取元数据,多次网络IO延迟累加后导致耗时拉长,本地磁盘场景下同规模文件检索耗时通常在1秒以内。
  • 原始代码存在几处可修复的问题:
    1. 函数调用放在函数定义之前,运行会触发NameError
    2. glob.iglob返回迭代器,直接用if not list_of_files判断永远为真,空文件场景下调用max()会抛出异常
    3. 匹配规则*.*txt会匹配文件名中带多个点的txt文件(如test.abc.txt),如果仅需要匹配后缀为.txt的文件,规则应改为*.txt

优化方案

使用os.scandir替代glob+os.path.getctime组合,os.scandir遍历目录时会批量拉取文件元数据,无需对每个文件单独发起IO请求,在网络共享路径场景下性能可提升数倍到数十倍。
优化后代码如下:

import os

def get_latest_file(path, suffix='.txt', recursive=True):
    latest_ctime = -1
    latest_file = ''
    for entry in os.scandir(path):
        # 跳过符号链接避免循环遍历
        if entry.is_dir(follow_symlinks=False):
            if recursive:
                sub_latest = get_latest_file(entry.path, suffix, recursive)
                if sub_latest:
                    sub_ctime = os.path.getctime(sub_latest)
                    if sub_ctime > latest_ctime:
                        latest_ctime = sub_ctime
                        latest_file = sub_latest
        elif entry.is_file(follow_symlinks=False) and entry.name.endswith(suffix):
            # 直接复用scandir返回的元数据,无需单独调用getctime
            current_ctime = entry.stat().st_ctime
            if current_ctime > latest_ctime:
                latest_ctime = current_ctime
                latest_file = entry.path
    return latest_file

# 函数调用需放在定义之后
path = 'C:\\Desktop\\Test'
latest_file = get_latest_file(path)

如果不需要递归遍历子目录,将recursive参数设为False可进一步缩短耗时。

内容的提问来源于stack exchange,提问作者CorgiGeek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 01:15:01