您可以使用搜索功能到达文件末尾并通过搜索换行符或其他方式找出最后日期。找到后,您可以进行相应的操作。我写了下面的脚本来找出每个文件的最后日期。此函数首先此函数查找给定日志文件中最后一个条目的日期。发现它从文件末尾开始并继续返回 2 个字符并检查下一个字符是否是换行符。当有换行符时,读取前 10 个字符。但是,当日志中有其他服务的异常时,行首可能不包含日期戳。因此,如果最后一行不包含日期戳,我们使用 try except 循环进一步迭代。
list= glob.glob("DebugLogFile.log*")
start_time = time.time()
def end_date(file):
count=0;
with open(file, "rb") as f:
first = f.readline()
# Read the first line.
`enter code here`f.seek(-2, os.SEEK_END)
#print f.tell() # Jump to the second last byte.
#print f.read(1)
flag=True;
while (flag) :
try :
#print f.tell()
f.seek(-2, os.SEEK_CUR)
while f.read(1) != b"\n": # Until EOL is found...
try:
f.seek(-2, os.SEEK_CUR)
#print f.tell()
except:
f.seek(0,os.SEEK_SET)
print "test"
break
#Remembering the current pointer in case we have to re-evaluate the date in case of exception
last_pos = f.tell()
last = f.readline()
date=last[:10]
datetime.datetime.strptime(date, '%Y-%m-%d').date()
flag=False
return datetime.datetime.strptime(date, '%Y-%m-%d').date()
except Exception, err_msg:
f.seek(last_pos)
def threshold(file):
base_date=end_date(file)
print("Base date is ", base_date)
print("Computing the threshold.......")
#convert the string to date object
#base_date_ob=datetime.datetime.strptime(base_date, '%Y-%m-%d').date()
threshold=base_date-timedelta(days=14)
return threshold
if __name__ == "__main__":
thresh=threshold("DebugLogFile.log")
print thresh
#list =['DebugLogFile.log.100']
#print list
for file in list :
tmp=end_date(file)
if(tmp>=thresh):
print ("Process file :", file, "Which has end date as ", tmp)
else:
print ("Do Not Process file :", file, "Which has end date as ", tmp)
time=time.time()