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

如何在Python中获取指定路径下PDF文件的最后修改日期

解决Python筛选PDF文件时的AttributeError问题

你遇到的错误是因为os.scandir()返回的是DirEntry对象,而非字符串文件名,所以不能直接调用endswith()方法。要对文件名做后缀判断,得调用file.name属性,同时建议先判断当前条目是文件而非文件夹,避免误处理目录。

修正后的代码如下:

import os
import datetime

path = "<insert path>"

def ts_to_dt(ts):
    return datetime.datetime.fromtimestamp(ts)

for file in os.scandir(path):
    # 先判断是文件,再匹配PDF后缀(兼容大小写)
    if file.is_file() and file.name.lower().endswith(".pdf"):
        print(file.name, ts_to_dt(file.stat().st_mtime))

关键修改说明:

  • 增加file.is_file()判断:过滤掉路径中的文件夹,只处理文件类型
  • 使用file.name.lower().endswith(".pdf"):通过file.name获取文件名,转小写后匹配后缀,能兼容.PDF这类大写后缀的情况
  • 可选替换st_atime为st_mtime:st_atime是文件最后访问时间,st_mtime是最后修改时间,更符合你要获取"最后修改日期"的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:25:37