delete_3_hours.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import os
  2. import shutil
  3. import time
  4. def dir_contains_file(dir_path):
  5. """检查目录下是否有非隐藏文件"""
  6. for root, dirs, files in os.walk(dir_path):
  7. for file in files:
  8. if not str(file).startswith('.'):
  9. return True
  10. return False
  11. def get_file_age_hours(path):
  12. """获取文件/目录的创建时间,返回已过去的小时数"""
  13. # Windows 使用 st_ctime 作为创建时间;Linux/mac 使用 st_ctime 是状态改变时间,st_birthtime 是创建时间
  14. if os.name == 'nt': # Windows
  15. create_time = os.stat(path).st_ctime
  16. else: # Linux / macOS
  17. stat = os.stat(path)
  18. create_time = stat.st_birthtime if hasattr(stat, 'st_birthtime') else stat.st_ctime
  19. # 计算当前时间与创建时间的差值(小时)
  20. current_time = time.time()
  21. age_seconds = current_time - create_time
  22. age_hours = age_seconds / 3600
  23. return age_hours
  24. # 目标目录
  25. read_dirs = [r'/data/wind_files/headquarter/scada/tmp/',
  26. r'/data/wind_files/headquarter/cms/tmp/',
  27. r'/data/wind_files/headquarter/scada/second/tmp'
  28. ]
  29. for read_dir in read_dirs:
  30. # 遍历目录
  31. for date_file in os.listdir(read_dir):
  32. date_path = os.path.join(read_dir, date_file)
  33. # 只处理目录
  34. if not os.path.isdir(date_path):
  35. continue
  36. # 两个条件:无有效文件 + 创建时间超过3小时
  37. if not dir_contains_file(date_path) and get_file_age_hours(date_path) > 3:
  38. print(f"准备删除空目录(超过3小时): {date_path}")
  39. # 取消注释即可真正执行删除
  40. shutil.rmtree(date_path)
  41. else:
  42. # 打印不满足条件的目录信息(可选)
  43. pass