zoukankan      html  css  js  c++  java
  • python使用笔记13--清理日志小练习

     1 '''
     2 写一个删除日志的程序,删除5天前或为空的日志,不包括当天的
     3 1.删除5天前的日志文件
     4 2.删除为空的日志文件
     5 '''
     6 import os
     7 import time
     8 
     9 def delete_logs_file():#清理日志
    10     for cur_dir,dirs,files in os.walk('logs'):
    11         print(cur_dir,dirs,files)
    12         if files:#当文件列表不为空是,开始删除
    13             for file_name in files:
    14                 file_time = get_filename_time(file_name)#获取文件名的时间
    15                 is_delete_file = check_time(file_time)
    16                 file_path = os.path.join(cur_dir,file_name)
    17                 if is_delete_file:
    18                     os.remove(file_path)
    19                 else:
    20                     if check_time_is_today(file_time):#文件时间不是今天
    21                         if check_file_content(file_path):#文件为空,可以删除
    22                             print('文件为空',file_path)
    23                             os.remove(file_path)
    24 
    25 
    26 
    27 def get_filename_time(file_name):#获取文件名中的时间
    28     if file_name:
    29         temp = file_name.split('_')
    30         file_name_time = temp[1][:10]
    31         return file_name_time
    32 
    33 def check_time_is_today(time_str):#判断时间是否为当天
    34     today = time.strftime('%Y-%m-%d')#获取当天的格式化时间
    35     if today == time_str:
    36         return False
    37     else:
    38         return True
    39 
    40 def check_time(time_str):#判断时间是否为5天前的时间
    41     now_time = time.time()#获取当前的时间戳
    42     day_ago = now_time-5*24*60*60#获取5天前的时间戳
    43     temp_time = time.strptime(time_str,'%Y-%m-%d')#获取传入时间的元组
    44     time_zone = time.mktime(temp_time)
    45     if time_zone <= day_ago:
    46         return True
    47     else:
    48         return False
    49 
    50 def delete_file(file_path):#删除指定文件
    51     os.remove(file_path)
    52 
    53 def check_file_content(file_path):#判断文件是否为空
    54     file_size = os.path.getsize(file_path)
    55     if file_size == 0:
    56         return True
    57     else:
    58         return False
    59 
    60 delete_logs_file()
    
  • 相关阅读:
    【引用】Android.mk简介
    android02android的四大组件
    rpm 安装指令全
    android04activity的布局管理器
    代码积累1统计图
    清除防火墙所有配置规则
    代码积累2tab页面滑动效果
    RHEL5 配置YUM源 安装RZSZ
    系统安全漏洞扫描软件
    liunx下防火墙的配置
  • 原文地址:https://www.cnblogs.com/cjxxl1213/p/12905031.html
Copyright © 2011-2022 走看看