案例一:
import os
import time
path = "logs"
tmp = 60 * 60 * 24 * 2 #几天
def str_to_timezone(str_time=None,format="%Y-%m-%d %H:%M:%S"):
'''
这个函数是格式化好的时间,转时间戳的,默认返回当前时间戳
:param str_time: 格式化好的时间
:param format: 时间格式
:return:
'''
if str_time:
t2 = time.strptime(str_time, format)
return int(time.mktime(t2))
else:
return int(time.time())
for cur_dir,dirs,files in os.walk(path):
for file in files:
if file.endswith(".log"):
file_date = file.split(".")[0].split("_")[-1]
today = time.strftime("%Y-%m-%d")
if file_date != today: #判断是否当天的文件
t = time.time() - tmp
file_timezone = str_to_timezone(file_date,"%Y-%m-%d")
abs_path = os.path.join(cur_dir,file)
if file_timezone < t or os.path.getsize(abs_path)==0:
os.remove(abs_path)
案例二:
import os
import time
star_path = '/Users/finup/PycharmProjects/tqz_code/day6/logs'
cur_time = time.strftime('%Y-%m-%d', time.localtime()) # 当天日期转为指定格式的字符串
cur_tuple = time.strptime(cur_time, "%Y-%m-%d") # 字符串转为时间元组
cur_mk = time.mktime(cur_tuple) # 时间元组转为时间戳
for cur_path, dirs, files in os.walk(star_path):
for file in files:
full_path = os.path.join(cur_path, file)
file_data = file.strip().split('_')[1].split('.')[0] # 提取文件名
file_tuple = time.strptime(file_data, "%Y-%m-%d") # 转成时间元组
file_mk = time.mktime(file_tuple) # 转为时间戳
day = int((cur_mk - file_mk) / (60 * 60 * 24)) # 计算天数差
if (os.path.getsize(full_path) == 0 and day > 0) or (day > 3): # 删除一天前的空文件 或者 删除三天前的日志
os.remove(full_path)