zoukankan      html  css  js  c++  java
  • 删除三天前日志和空的文件代码

    造日志的脚本如下:

    import time
    import os
    import random


    def timestamp_to_str(timestamp=None, f='%Y-%m-%d %H:%M:%S'):
    """时间戳转格式化好的时间,如果没有传时间戳,就获取当前的格式化时间"""
    if timestamp:
    time_tuple = time.localtime(timestamp) # 把时间戳转成时间元组
    result = time.strftime(f, time_tuple) # 把时间元组转成格式化好的时间
    return result
    else:
    return time.strftime(f)


    lis = ['ios', 'android', 'nginx', 'tomcat', 'python', 'blog', 'apache', 'mysql', 'redis']
    for i in lis:
    p = os.path.join('logs', i)
    os.makedirs(p)
    for j in range(30):
    t = int(time.time())-86400*j
    time_str = timestamp_to_str(t, '%Y-%m-%d')
    log_name = '%s_%s.log' % (i, time_str)
    abs_file_path = os.path.join('logs', i, log_name)
    fw = open(abs_file_path, 'w', encoding='utf-8')
    if random.randint(1, 10) % 2 == 0:
    fw.write('胜多负少防守打法双方都')
    fw.close()

    运行脚本后在当前路径下生成若干个文件夹,每个文件夹下面有30个文件,随机往每个文件里写入内容,有的文件为空,接下来删除三天前的日志和空文件的代码如下:

    import os
    import time


    def str_to_timestamp(string=None, format='%Y-%m-%d %H:%M:%S'):
    """把格式化好的时间字符串转成时间戳,默认返回当前时间戳"""
    import time
    if string:
    time_tuple = time.strptime(string, format)
    res = time.mktime(time_tuple)
    else:
    res = time.time()
    return int(res)


    def clean_logs(path, days=3):
    if not os.path.isdir(path):
    print('您传入的不是一个文件夹')
    return
    for cur_dir, dirs, files in os.walk(path):
    for file in files:
    if file.endswith('.log'):
    prefix = file.split('.')[0] # file类型是tomcat_2020-04-15.log,先以.分割取前面的
    file_time = prefix.split('_')[-1] # 将tomcat_2020-04-15以_分割取出格式化的时间
    file_time_stamp = str_to_timestamp(file_time, '%Y-%m-%d') # 将2020-04-15转成时间戳
    three_day_ago = time.time() - 60 * 60 * 24 * days # 三天前的时间戳
    file_path = os.path.join(cur_dir, file)
    # 删除三天前的日志和空的文件
    if file_time_stamp < three_day_ago or os.path.getsize(file_path) == 0:
    os.remove(file_path)


    clean_logs('logs') 
  • 相关阅读:
    第11组 团队Git现场编程实战
    第11组 团队项目-需求分析报告
    团队项目-选题报告
    第二次结对编程作业
    第11组 团队展示
    第一次结对编程作业
    Nginx学习笔记
    Git学习笔记
    Qt学习笔记
    Eclipse中Outline里各种图标的含义
  • 原文地址:https://www.cnblogs.com/laosun0204/p/10980548.html
Copyright © 2011-2022 走看看