import os,time
#格式化时间转时间戳
def strToTimestamp(time_str,format='%Y%m%d%H%M%S'):
t = time.strptime(time_str,format)#格式化时间转化为时间元组
res = time.mktime(t)#时间元组转化为时间戳
return res
#时间戳转格式化时间
def timestampToStr(time_stamp,format='%Y%m%d%H%M%S'):
cur_time=time.localtime(time_stamp)#时间戳转化为时间元组
res = time.strftime(format,cur_time)#元组转化为格式化时间
return res
def clean_log(path):
#判断路径是否存在是文件夹
if os.path.exists(path) and os.path.isdir(path):
today = time.strftime('%Y-%m-%d')#20170102
cur_stamp = strToTimestamp(today,'%Y-%m-%d')
yesterday_stamp=cur_stamp-60*60*24
before_yesterday_stamp=yesterday_stamp-60*60*24
time_list=[timestampToStr(yesterday_stamp,'%Y-%m-%d'),today,timestampToStr(before_yesterday_stamp,'%Y-%m-%d')]
for file in os.listdir(path):
file_name_sp=file.split('.')
if len(file_name_sp)>2:
file_date = file_name_sp[1]
if file_date not in time_list:
abs_path=os.path.join(path,file)
print('删除的文件是:%s'%abs_path)
os.remove(abs_path)
else:
print('没有删除的文件是:%s'%file)
else:
print('路径不存在/不是目录')
clean_log(r'logs')
转载于:https://www.cnblogs.com/luonanhenniu/p/9398377.html