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

如何在Databricks的Python环境中删除目录下30天前的文件?

解决按日期目录结构删除过期文件的问题

原代码的核心问题

  • 硬编码单一文件路径,无法批量处理目录中大量文件
  • 仅提取日期的“日”部分计算差值,完全忽略年、月维度,跨月/跨年时逻辑彻底失效
  • 未导入os模块却调用os.remove
  • 通过字符串截取处理日期的方式容错性极差,容易出错

正确实现方案

下面的代码会遍历model目录下的年/月/日层级结构,解析每个文件所在的日期,与当前日期往前推30天的阈值对比,自动删除过期文件:

import os
from datetime import datetime, timedelta

def cleanup_model_output(root_dir, days_to_keep=30):
    # 计算过期阈值:当前日期往前推days_to_keep天
    threshold_date = datetime.now().date() - timedelta(days=days_to_keep)
    
    # 逐层遍历年、月、日目录
    for year_dir in os.listdir(root_dir):
        if not year_dir.isdigit():
            continue
        year_path = os.path.join(root_dir, year_dir)
        if not os.path.isdir(year_path):
            continue
        
        for month_dir in os.listdir(year_path):
            if not (month_dir.isdigit() and len(month_dir) == 2):
                continue
            month_path = os.path.join(year_path, month_dir)
            if not os.path.isdir(month_path):
                continue
            
            for day_dir in os.listdir(month_path):
                if not (day_dir.isdigit() and len(day_dir) == 2):
                    continue
                day_path = os.path.join(month_path, day_dir)
                if not os.path.isdir(day_path):
                    continue
                
                # 解析目录对应的日期
                try:
                    file_date = datetime(int(year_dir), int(month_dir), int(day_dir)).date()
                except ValueError:
                    # 跳过无效日期格式的目录
                    continue
                
                # 判断是否过期并删除文件
                if file_date < threshold_date:
                    for filename in os.listdir(day_path):
                        file_path = os.path.join(day_path, filename)
                        if os.path.isfile(file_path):
                            os.remove(file_path)
                    # 可选:如果需要删除空目录,取消下面注释
                    # os.rmdir(day_path)

# 使用示例:替换为你的model目录根路径
cleanup_model_output("C:/path/to/your/model")

代码关键点说明

  • 层级遍历:自动遍历所有符合年/月/日结构的目录,跳过非数字格式的无效目录
  • 日期处理:直接从目录名解析年、月、日并转换为date对象,彻底避免字符串截取的错误
  • 阈值计算:用timedelta计算过期日期,跨月、跨年场景下逻辑完全准确
  • 批量处理:无需硬编码单个文件路径,自动处理目录中所有符合规则的文件
  • 容错机制:捕获无效日期的异常,避免程序意外崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:57:20