You need to enable JavaScript to run this app. 如何使用pandas按修改日期获取目录下指定格式的文件列表
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pandas按修改日期获取目录下指定格式的文件列表

按修改日期筛选匹配文件的实现方案

原有代码问题梳理

  • 路径与文件名通配符拼接时缺少分隔符,会生成C:\pythonaaaa*error_*.csv.bz2这类错误路径,导致glob匹配不到任何文件
  • 仅获取了目标目录本身的修改时间,并非目录下文件的最新修改时间
  • 没有新增文件修改日期的比对逻辑,同时无退出条件的while循环会成为死循环

完整实现代码

import glob
import os
import time

error_file_path = "C:\\python"
# 拼接合法的文件匹配规则,自动适配操作系统路径分隔符
file_pattern = os.path.join(error_file_path, "aaaa*error_*.csv.bz2")

# 第一步:获取所有匹配文件的最新修改日期作为筛选基准
latest_timestamp = 0
for file_path in glob.glob(file_pattern):
    current_timestamp = os.path.getmtime(file_path)
    if current_timestamp > latest_timestamp:
        latest_timestamp = current_timestamp
# 转换为统一格式的日期字符串
target_date = time.strftime("%d/%m/%Y", time.localtime(latest_timestamp))

# 第二步:筛选出修改日期等于目标日期的所有文件
matched_files = []
for file_path in glob.glob(file_pattern):
    file_modify_date = time.strftime("%d/%m/%Y", time.localtime(os.path.getmtime(file_path)))
    if file_modify_date == target_date:
        matched_files.append(file_path)

print(matched_files)

自定义调整说明

如果不需要自动取最新文件的日期作为筛选基准,直接给target_date赋值指定日期即可,格式要和转换逻辑保持一致,例如:

# 直接指定筛选2024年10月25日的文件
target_date = "25/10/2024"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 23:24:02