码迷,mamicode.com
首页 > 其他好文 > 详细

删除历史日志文件

时间:2018-07-31 23:26:22      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:存在   strtotime   删除   import   file   时间   print   else   port   

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‘)

删除历史日志文件

标签:存在   strtotime   删除   import   file   时间   print   else   port   

原文地址:https://www.cnblogs.com/luonanhenniu/p/9398377.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!