PYTHON提取TXT或log内容

import osimport reimport tkinter as tkfrom tkinter import filedialogroot = tk.Tk()root.withdraw()Files_r = filedialog.askopenfilenames(title="选择要转换历史告警log文件",filetypes=[('log、TXT文件', '*.log;*.txt')])# 获得选择好的文件if not Files_r:print("没有选中文件夹,请重新选择!")else:Files_t=filedialog.asksaveasfilename(title="提取结果另存为:", filetype=[('csv文件', '*.csv')])if not Files_t:print("没有选择并输入要保存的文件名,请重新选择!")else:linenum=0with open(Files_t+".csv",'w') as r_f:r_f.write("ip"+chr(44)+"Timestamp"+chr(44)+"S Problem "+chr(44)+"MO (Cause)"+chr(44)+"name"+'n')r_f.closedfor j in Files_r:with open(j) as f:file1 = f.readlines()linenum = -1st=0end=0for line in file1:linenum = linenum + 1if line.find('> q')>-1:end=linenumif line.find('Timestamp')>-1:st=linenumif st>0:x=0y=0for i in range(st,end):iffile1[i].find('Timestamp')>-1:x = file1[i].find('S Problem')y=file1[i].find('MO (Cause')if file1[i].find('Timestamp')==-1 andfile1[i].find('==')==-1 andfile1[i].count('n')!=len(file1[i]):t1=(file1[i][0:x])t2=(file1[i][x:y])t3=(file1[i][y:len(file1[i])]).replace(","," ").strip()#rr=re.compile(r"EUtranCellTDD=(w+-w+-d+)|EUtranCellFDD=(+w+-w+-d+)")name_t3=t3.split(" ")[0]t4=name_t3.replace("EUtranCellTDD=","").replace("EUtranCellFDD=","").strip('n')with open(Files_t+'.csv','a') as r_f:r_f.write(str(j)+chr(44)+chr(34)+t1+chr(34)+chr(44)+t2+chr(44)+chr(34)+t3+chr(34)+chr(44)+t4+"n")print(str(j)+" is done!")print("All is done!")
【PYTHON提取TXT或log内容】


    推荐阅读