练习2:清理指定天数前的日志

需求:测试机器的磁盘太小,经常报警,要写一个清理日志的脚本,每次运行就把三天之前的日志删除,日志名的格式是xxx-20170623.log

步骤:
# 1、获取目录下的所有文件名
# 2、将以.log结尾的文件前面的日期取出来
# 3、判断,如果是三天前的删除

import os,time,datetime

def strtotimestamp(str=None,format='%Y-%m-%d'):
    if str:
        tp = time.strptime(str,format)  #Parse a string to a time tuple according to a format specification.
        res = time.mktime(tp)
        #Convert a time tuple in local time to seconds since the Epoch(1970-01-01 00:00:00 UTC)
        #时间元组转换为时间戳
    else:
        res = time.time() #Return the current time in seconds since the Epoch获取当前时间戳
        #不做处理,时间戳为 float 类型
    return int(res)

def delbeforedaysfile(filepath,duration):
    duration_new = duration.__neg__()  #取负数
    day_delduration = datetime.date.today() + datetime.timedelta(duration_new)
    #print(day_delduration) 2018-06-10
    #day_delduration2= datetime.datetime.now() +datetime.timedelta(duration_new)
    #print(day_delduration2) 2018-06-10 18:32:01.653400
    #abspath,dir,file = os.walk(filepath)
    for abspath,dir,file in os.walk(filepath):
        for filename in file:
            if filename.split('.')[1] == 'log': #后缀不为.log 的文件不处理
                filename_del = os.path.join(abspath, filename)
                front_filename = filename.split('.')[0]
                date_filename = front_filename.split('_')[2]
                #日志文件的格式为Parking_error_20180614.log,所以format的格式需要传入,不使用默认
                if strtotimestamp(str(day_delduration))> strtotimestamp(str=date_filename,format='%Y%m%d'):
                    os.remove(filename_del)
                    print('删除%d天前的文件%s成功' %(duration, filename))

猜你喜欢

转载自www.cnblogs.com/liuyanerfly/p/9184090.html