# coding=UTF-8
# This Python file uses the following encoding: utf-8
import os, time, re, sys
nowDate = time.strftime('%Y%m%d')
lens = 2
def days(str1, str2):
date1 = time.strptime(str1, '%Y%m%d')
date2 = time.strptime(str2, '%Y%m%d')
num = (date1 - date2).days
return num
def months(str1, str2):
year1 = time.strptime(str1, '%Y%m%d').tm_year
year2 = time.strptime(str2, '%Y%m%d').tm_year
month1 = time.strptime(str1, '%Y%m%d').tm_mon
month2 = time.strptime(str2, '%Y%m%d').tm_mon
num = (year1 - year2) * 12 + (month1 - month2)
return num
def foreach(path):
print("准备执行文件查询")
deleteArr = []
for fileobj in os.listdir(path):
logFileTime = re.findall(r'\d{8}', fileobj.replace('-', ''))
if len(logFileTime) > 0:
if months(nowDate, logFileTime[0]) > lens:
deleteArr.append(path + '/' + fileobj)
print("合规数据长度:", len(deleteArr))
return deleteArr
def deleFile(filePath):
print("即将删除文件:" + filePath);
os.remove(filePath)
print("已删除文件:" + filePath);
def manfun(arr):
path = arr[1];
if len(arr) == 2:
if not os.path.isdir(path):
print('请输入正确的文件夹目录')
print('默认保留90天 正确格式 :python cleanLogfile.py /data/dev_apps/order-pay/logs ')
print('指定时间正确格式 :python cleanLogfile.py /data/dev_apps/order-pay/logs 90 ')
elif len(arr) == 3:
if not isinstance(arr[2], int):
print('指定时间正确格式 :python cleanLogfile.py "/data/dev_apps/order-pay/logs" 90 ')
else:
lens = int(arr[2])
else:
print('默认保留90天 正确格式 :python cleanLogfile.py /data/dev_apps/order-pay/logs ')
print('指定时间正确格式 :python cleanLogfile.py "/data/dev_apps/order-pay/logs" 90 ')
for filePath in foreach(path):
deleFile(filePath)
if __name__ == '__main__':
manfun(sys.argv)
|