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

使用glob.glob和max(os.path.getctime)获取最新文件名优化方案

如何快速从网络驱动器获取最新文件?

我需要从存有数百个文件的网络驱动器目录中获取最新文件的文件名,计划每次运行脚本时提取文件名(文件名包含下载时间,例如xyz201912191455.csv)并写入配置文件。目前list_of_files执行耗时约1秒,但latest_file执行耗时高达100秒,速度极慢。请问是否有更快的获取最新文件信息的方法?

用户提供的代码示例:

import os
import glob
import time
from configparser import ConfigParser
import configparser

list_of_files = glob.glob('filepath\\*', recursive=True)
latest_file = max(list_of_files, key=os.path.getctime)
list_of_files2 = glob.glob('filepath\\*', recursive=True)
latest_file2 = max(list_of_files2, key=os.path.getctime)

优化方案

  • 利用文件名中的时间戳直接排序
    既然你的文件名本身就包含了标准格式的下载时间,这绝对是最快的优化方向!完全不需要去远程访问每个文件的系统属性,直接从文件名里提取时间字符串做比对就行。
    举个适配你文件名格式的例子:

    import glob
    import os
    
    list_of_files = glob.glob('filepath\\*', recursive=True)
    # 提取文件名中.csv前的12位时间字符串(YYYYMMDDHHMM格式)
    latest_file = max(list_of_files, key=lambda x: os.path.basename(x)[-16:-4])
    

    字符串比对的速度比远程请求文件属性快几个数量级,能直接把100秒的耗时压到毫秒级。

  • 砍掉重复的目录遍历
    看你的代码里两次调用了glob.glob('filepath\\*', recursive=True),这完全是做重复工作!只需要遍历一次目录,把结果存下来复用就能省掉1秒的额外耗时:

    list_of_files = glob.glob('filepath\\*', recursive=True)
    latest_file = max(list_of_files, key=...)
    # 直接复用上面的list_of_files,不用再重新遍历
    latest_file2 = max(list_of_files, key=...)
    
  • 用os.scandir()优化文件属性获取(如果必须依赖系统时间)
    如果你因为特殊原因不能用文件名的时间戳,那可以用os.scandir()代替glob。os.scandir()在遍历目录时会一次性缓存文件的属性信息,避免了单独调用os.path.getctime()时的多次远程IO请求,能大幅降低耗时:

    import os
    
    latest_ctime = 0
    latest_file = ""
    with os.scandir('filepath') as entries:
        for entry in entries:
            if entry.is_file():
                current_ctime = entry.stat().st_ctime
                if current_ctime > latest_ctime:
                    latest_ctime = current_ctime
                    latest_file = entry.path
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:53:07