删除N天前文件和空文件

需求:

  1. 使用指定的代码自动的生成一些文件
  2. 写代码,自动的删除时间是3天的文件和空的文件
#指定的代码生成小程序

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


import time,os,random
l = ['ios','android','nginx','tomcat','python','blog','apache','mysql','redis']

for i in l:
    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()

 代码实现:

# 分析
#1、获取到logs目录下所有的日志文件 os.walk()
#2、获取日志文件的时间,android_2021-06-24.log,使用.split取出时间部分
#3、判断是否是3天前的时间,现在的时间 - 60*60*24*3,3天前的删除
#4、判断每个文件是否为空 ,为空的删除

import os
import time

def str_to_timestamp(string=None,format='%Y-%m-%d'):
    '''格式化好的字符串转时间戳,默认返回当前时间戳'''
    if string:
        time_tuple = time.strptime(string, format)  # 格式化好的时间,转时间元组的
        result = time.mktime(time_tuple)  # 把时间元组转成时间戳
    else:
        result = time.time() # 获取当前时间戳
    return int(result)
def del_file(day=3):
    path = input('请输入当前路径:').strip()
    if not os.path.exists(path):
        print('此路径不存在')
        return
    for cur_path,dirs,files in os.walk(path):
        for d in files:
            if d.endswith('.log'):
                file_time = d.split('_')[-1].split('.')[0]
                timezone = str_to_timestamp(file_time,'%Y-%m-%d')
                abs_path = os.path.join(cur_path,d)
                if timezone <= (time.time()-(60*60*24*day)):
                    os.remove(abs_path)
                elif os.path.getsize(abs_path)==0:
                    os.remove(abs_path)
del_file()
原文地址:https://www.cnblogs.com/brf-test/p/14934652.html