import os import shutil import time def dir_contains_file(dir_path): """检查目录下是否有非隐藏文件""" for root, dirs, files in os.walk(dir_path): for file in files: if not str(file).startswith('.'): return True return False def get_file_age_hours(path): """获取文件/目录的创建时间,返回已过去的小时数""" # Windows 使用 st_ctime 作为创建时间;Linux/mac 使用 st_ctime 是状态改变时间,st_birthtime 是创建时间 if os.name == 'nt': # Windows create_time = os.stat(path).st_ctime else: # Linux / macOS stat = os.stat(path) create_time = stat.st_birthtime if hasattr(stat, 'st_birthtime') else stat.st_ctime # 计算当前时间与创建时间的差值(小时) current_time = time.time() age_seconds = current_time - create_time age_hours = age_seconds / 3600 return age_hours # 目标目录 read_dirs = [r'/data/wind_files/headquarter/scada/tmp/', r'/data/wind_files/headquarter/cms/tmp/', r'/data/wind_files/headquarter/scada/second/tmp' ] for read_dir in read_dirs: # 遍历目录 for date_file in os.listdir(read_dir): date_path = os.path.join(read_dir, date_file) # 只处理目录 if not os.path.isdir(date_path): continue # 两个条件:无有效文件 + 创建时间超过3小时 if not dir_contains_file(date_path) and get_file_age_hours(date_path) > 3: print(f"准备删除空目录(超过3小时): {date_path}") # 取消注释即可真正执行删除 shutil.rmtree(date_path) else: # 打印不满足条件的目录信息(可选) pass