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

Python按修改日期高效加载目录及筛选近24小时文件方案

高效筛选目录中近24小时修改的文件

你的问题核心是遍历大量文件时重复调用系统接口导致的性能损耗,以下是更快捷的实现方式:

最优方案:使用os.scandir()

os.scandir()是Python 3.5+引入的API,它在遍历目录时会批量获取文件的元数据(包括修改时间),避免了os.listdir()+os.path.getmtime()组合中对每个文件单独发起系统调用的开销,在大目录下性能提升显著。

同时修复原代码中未拼接完整文件路径的潜在问题,完整代码示例:

import os
from datetime import datetime, timedelta

dir_path = "/目标目录路径"
now = datetime.now().timestamp()
# 提前计算24小时前的时间戳,避免循环内重复计算
time_threshold = now - timedelta(hours=24).total_seconds()

# 使用上下文管理器自动释放资源
with os.scandir(dir_path) as entries:
    for entry in entries:
        # 按需过滤:只处理文件(跳过目录)
        if entry.is_file():
            mtime = entry.stat().st_mtime
            if time_threshold <= mtime <= now:
                do_something(entry.path)  # entry.path直接提供完整文件路径

额外优化建议

  • 若只需处理特定类型文件,可在循环内增加文件名后缀判断(如entry.name.endswith('.txt')),减少不必要的时间戳判断
  • 对于超大规模目录,可考虑结合多进程/多线程并行处理,但需注意文件系统的IO瓶颈

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 11:11:01