import os
from datetime import datetime
import logging
#定义日志级别
logging.basicConfig(level=logging.DEBUG, filename='E:/游戏数据备份/log_file_del.log',filemode='a',format='%(asctime)s - %(levelname)s: %(message)s')
def delete_expired_files(directory):
for root, dirs, files in os.walk(directory):
for file in files:
# 获取当前时间与文件修改时间之间的天数差值
days = (datetime.now() - datetime.fromtimestamp(os.path.getmtime(os.path.join(root, file)))).days
if days > 3: # 设置过期时间为30天
try:
os.remove(os.path.join(root, file))
#logging.info("已成功删除文件:%s" %(os.path.join(root, file)) )
except Exception as e:
logging.error("无法删除文件:%s, 错误信息:" %( os.path.join(root, file), str(e) ))
# 调用示例
#if __name__ == '__main__':
delete_expired_files('E:/游戏数据备份')