##批量## import os import pandas as pd #1,遍历目录下的文件 path = r"F:\项目\国美新\log\4-26/" file_list = os.listdir(path) #2,设置需要匹配的关键词列表 kws = ["bad", "faild", "FAULTY", "error"] #定义一个字典 get_result = [] #3,循环打开文件 for lines in file_list: with open(os.path.join(path+lines), 'r', encoding='utf-8', errors='ignore') as f: #4,循环逐行读取内容 for i in f.readlines(): #5,比对文件中是否匹配自定义列表的关键字,出现则记录 if (any(kw in i for kw in kws)): get_result.append([lines, i]) #6,记录日志到excel name = ['host', 'txt'] contents = pd.DataFrame(columns=name, data=get_result) contents.to_csv('log.csv', encoding='utf-8')
标签:get,lines,关键字,文件夹,result,path,日志,os From: https://www.cnblogs.com/dengcongcong/p/16788166.html