需要从txt文档中筛选出某些字段,写了个python小脚本去执行。
import os
##获取当前路径
curpath=os.getcwd()
##列出路径下的所有文件,方便获得txt文档的名称
pathdir=os.listdir(curpath)
txtfilename=''
filename=[]
##获取的名称是带有文件后缀的,使用split直接筛选出.txt的文件
for i in pathdir:
filename=i.split('.')
if filename[1] == 'txt':
txtfilename=i
break
##因为文档大部分为gbk编码,ignore忽略掉其他编码格式,不然会报错
fr=open(logfilename,'r',encoding='gbk',errors='ignore')
##按行读取
all_lines=fr.readlines()
##按条件需要筛选
dataset=[]
tag=''
finaldata=[]
for line in all_lines:
dataset=line.split(': ')
tag=dataset[0]
splitstag1='te'
splitstag2='st'
if tag.find(splitstag1) != -1:
dataset=tag.split(splitstag1)
tag=dataset.pop()
else:
dataset=tag.split(splitstag2)
tag=dataset.pop()
##如果当前行筛选出来的结果之前没有的,使用append新增到列表后
if tag not in finaldata:
finaldata.append(tag)
##创建一个筛选结果txt文档,将筛选结果写入
rsfile="ReadResult.txt"
if os.path.exists(rsfile):
os.remove(rsfile)
file = open(rsfile, "w")
for i in finaldata:
file.write(i)
file.write('\n')
file.close()
print("work down!")