#coding=utf-8 import os import time import datetime def deleteOutdateFiles(path): """ 删除目录下七天前创建的文件 """ current_time = time.strftime("%Y-%m-%d", time.localtime(time.time())) current_timeList = current_time.split("-") current_time_day = datetime.datetime(int(current_timeList[0]), int(current_timeList[1]), int(current_timeList[2])) for root, dirs, files in os.walk(path): for item in files: file_path = os.path.join(root, item) create_time = time.strftime("%Y-%m-%d", time.localtime((os.stat(file_path)).st_mtime)) create_timeList = create_time.split("-") create_time_day = datetime.datetime(int(create_timeList[0]), int(create_timeList[1]), int(create_timeList[2])) time_difference = (current_time_day - create_time_day).days if time_difference > 7: os.remove(file_path)