1 #删掉三天前的日志
2 #1、获取到所有的日志文件, os.walk
3 #2、获取文件时间 android 2019-09-27 log,并转成时间戳
4 #3、获取3天前的时间 time.time() - 60 * 60 *24 *3
5 #4、判断文件的时间戳如果小于3天前的时间戳删除
6 #5、文件为空删除 os.path.getsize()
7
8 import os,time
9 import random
10
11
12 def str_to_timestamp(string=None,format='%Y-%m-%d %H:%M:%S'):
13 '''格式化好的字符串转时间戳,默认返回当前时间戳'''
14 if string:
15 time_tuple = time.strptime(string, format) # 格式化好的时间,转时间元组的
16 result = time.mktime(time_tuple) # 把时间元组转成时间戳
17 else:
18 result = time.time()
19 return int(result)
20
21 def clean_logs(path,days=3):
22 if not os.path.isdir(path):
23 print("传入的不是一个文件夹")
24 return
25 for cur_dir,dirs,files in os.walk(path):
26 for file in files:
27 if file.endswith('.log'):
28 # file_time = file.split('.')[0].split('_')[-1]
29 prefix=file.split('.')[0]
30 file_time = prefix.split('_')[-1]
31 file_time_stamp = str_to_timestamp(file_time,'%Y-%m-%d')
32 three_day_ago = time.time() - 60 * 60 * 24 * days
33 file_path = os.path.join(cur_dir,file)
34 if file_time_stamp < three_day_ago or os.path.getsize(file_path)==0:
35 os.remove(file_path)