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

调用os.path.getatime获取文件Unix访问时间戳触发FileNotFoundError问题

错误原因

os.walk() 遍历目录时返回的 filenames 仅存储纯文件名,不包含文件所在的目录路径。你直接将纯文件名传入os.path.getatime()时,Python默认只会在当前脚本的运行工作目录下查找对应文件,而目标文件实际存放在root变量对应的子目录中,路径不匹配就会触发文件不存在的报错。

解决方法

每次操作文件前,先拼接得到文件的完整绝对路径,后续所有获取文件属性的操作都基于这个完整路径执行即可,修改后的核心代码如下:

for root, subfolder, filenames in os.walk(main_path):
    for file in filenames:
        # 拼接得到文件完整路径
        full_file_path = os.path.join(root, file)
        unix_arquivo = os.path.getatime(full_file_path)
        if data_hoje - unix_arquivo >= tres_meses:
            nome = os.path.basename(file)
            acesso = datetime.utcfromtimestamp(os.path.getatime(full_file_path)).strftime('%Y-%m-%d')
            modificacao = datetime.utcfromtimestamp(os.path.getmtime(full_file_path)).strftime('%Y-%m-%d')
            frutas_page.append([nome, acesso, modificacao])

可选优化:如果遍历的目录里存在系统级无访问权限的文件,可以加异常捕获避免程序中途中断:

for root, subfolder, filenames in os.walk(main_path):
    for file in filenames:
        full_file_path = os.path.join(root, file)
        try:
            unix_arquivo = os.path.getatime(full_file_path)
        except (FileNotFoundError, PermissionError):
            # 跳过无法访问的文件
            continue
        if data_hoje - unix_arquivo >= tres_meses:
            nome = os.path.basename(file)
            acesso = datetime.utcfromtimestamp(os.path.getatime(full_file_path)).strftime('%Y-%m-%d')
            modificacao = datetime.utcfromtimestamp(os.path.getmtime(full_file_path)).strftime('%Y-%m-%d')
            frutas_page.append([nome, acesso, modificacao])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 14:09:04