import os import time from datetime import datetime, timedelta # 用户可以在此处修改要清理的目录 TARGET_DIR = "E:\pythontest\CLEAN_EVERYTHING\新建文件夹" # 请将此路径修改为实际要清理的目录 def clean_log_files(directory): # 获取脚本所在目录 script_dir = os.path.dirname(os.path.abspath(__file__)) # 创建日志文件路径 log_file = os.path.join(script_dir, 'clean_logs_history.log') # 清理超过7天的日志记录 if os.path.exists(log_file): with open(log_file, 'r+', encoding='utf-8') as f: lines = f.readlines() f.seek(0) for line in lines: log_time_str = line.split(' - ')[0] log_time = datetime.strptime(log_time_str, '%Y-%m-%d %H:%M:%S') if datetime.now() - log_time <= timedelta(days=7): f.write(line) f.truncate() total_size = 0 # 初始化总大小统计 deleted_count = 0 # 初始化删除文件计数 # 遍历目录并删除.log文件 for root, dirs, files in os.walk(directory): for file in files: if file.endswith('.log'): file_path = os.path.join(root, file) try: file_size = os.path.getsize(file_path) # 获取文件大小 os.remove(file_path) # 记录删除操作 size_mb = round(file_size / (1024 * 1024), 2) # 转换为MB with open(log_file, 'a', encoding='utf-8') as f: f.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Deleted: {file_path} ({size_mb} MB)\n") print(f"Deleted: {file_path} ({size_mb} MB)") total_size += file_size deleted_count += 1 except Exception as e: print(f"Error deleting {file_path}: {e}") # 记录本次清理的总大小 if deleted_count > 0: total_mb = round(total_size / (1024 * 1024), 2) # 转换为MB with open(log_file, 'a', encoding='utf-8') as f: f.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Total: Deleted {deleted_count} files, {total_mb} MB\n") if __name__ == "__main__": if os.path.isdir(TARGET_DIR): clean_log_files(TARGET_DIR) print("清理完成") else: print(f"无效的目录路径: {TARGET_DIR}")