1. 程式人生 > 實用技巧 >python日誌的清理

python日誌的清理

需求:

1、寫一個清理日誌的程式碼
1.1、刪除3天前的日誌檔案
1.2、刪除檔案內容為空的日誌檔案
1.3、如果當天的日誌檔案為空,不刪除

import os,sys
# print(os.getcwd())
# print(os.listdir())
# C:\Users\Administrator\Desktop\TQZ\day06\logs
import datetime,time
key_word = 24 * 60 * 60
star_path = '/Users/Administrator/Desktop/TQZ/day06/logs'
time_str = time.strftime('%Y-%m-%d', time.localtime()) # 當天日期轉為指定格式的字串
print(time_str)
# print(type(time_str))
time_tuple = time.strptime(time_str, "%Y-%m-%d") # 字串轉為時間元組
print(time_tuple)
# print(type(time_tuple))
cur_mk = time.mktime(time_tuple) # 時間元組轉為時間戳
print(cur_mk)
# print(type(cur_mk))
for cur_path,dirs,files in os.walk('/Users/Administrator/Desktop/TQZ/day06/logs'):
for file in files:
full_path = os.path.join(cur_path,file)
# if file.endswith(key_word) and os.path.getsize(full_path) <= size:
fill_date = file.strip().split('_')[1].split('.')[0]
# print(fill_date)
file_tuple = time.strptime(fill_date,'%Y-%m-%d')
# print(file_tuple)
file_mk = time.mktime(file_tuple)
# print(file_mk)
day = int(cur_mk-file_mk) / key_word
print(day)
if (os.path.getsize(full_path) ==0 and day > 0) or day > 3:
os.remove(full_path)