import os
import time
import datetime
def get_fileCreateTime(filePath):
"""获取文件创建时间距离今天的天数"""
timestamp = os.path.getctime(filePath)
timestruct = time.localtime(timestamp)
file_create_time = time.strftime('%Y-%m-%d', timestruct)
current_time = time.strftime('%Y-%m-%d')
day1 = datetime.datetime.strptime(file_create_time, '%Y-%m-%d')
day2 = datetime.datetime.strptime(current_time, '%Y-%m-%d')
delta = day2 - day1
return delta.days
def getfile_list():
"""遍历指定目录获取大于指定天数的文件"""
file_list = []
del_file_list = []
day = 0
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
for root, dirs, files in os.walk(BASE_DIR):
[del_file_list.append({"filename": root+"/"+files[i]}) for i in range(len(files)) if get_FileCreateTime(root+"/"+files[i]) > day]
return del_file_list
def del_files():
"""遍历删除文件"""
file_list = getfile_list()
for temp in file_list:
if os.path.exists(temp["filename"]):
os.remove(temp["filename"])
else:
print('no such file:%s' % temp["filename"])
del_files()
|