如何让Python读取日志文件时匹配到首个CPU利用率结果后停止?
Fix: Stop Writing After First Match of CPU Utilization in Each Log File
我看你遇到的问题是每个日志文件里的Core0和Core1 CPU利用率记录被重复写入Excel了——这是因为你的代码在遍历文件行的时候,只要碰到匹配的行就会写入,完全没考虑「只取第一个匹配项」的需求。咱们来调整代码,让它找到每个核心的第一条记录后就停止处理当前文件的后续行。
核心解决思路
- 给每个文件设置两个跟踪标志:
found_core0和found_core1,用来标记是否已经找到对应核心的第一条CPU记录 - 遍历文件行时,只有当对应标志为
False(还没找到)时,才执行写入操作,并把标志设为True - 一旦两个标志都变为
True(两个核心的第一条记录都找到了),直接跳出当前文件的行循环,去处理下一个文件
修改后的完整代码
import os import xlsxwriter import re MyPath = "FileDirectory" # e.g. "MyDocuments/Python" MyHost = "Hostname" # e.g. "Router1_Loc1" Host_Probes = [] # Loop: Populate Host_Probes [] for root, dirs, files in os.walk(MyPath, topdown=False): for names in files: if MyHost in names: Host_Probes.append(os.path.join(names)) # List with locations of all log files for the TargetHost Probe_Paths = [os.path.join(MyPath, s) for s in Host_Probes] # 改用os.path.join更安全,避免路径拼接出错 # Excel file and sheet: workbook = xlsxwriter.Workbook('MyFile.xlsx') # 修正引号语法错误 worksheet = workbook.add_worksheet('Sheet1') row = 2 # Row:3 col = 2 # Col:C for s in Probe_Paths: found_core0 = False found_core1 = False with open(s) as Probe: for fileLine in Probe: # 处理Core0:仅当未找到时才写入 if not found_core0 and "Core0: CPU utilization" in fileLine: worksheet.write(row, col, int(re.sub('[^0-9]', '', fileLine))) found_core0 = True # 处理Core1:仅当未找到时才写入 elif not found_core1 and "Core1: CPU utilization" in fileLine: worksheet.write(row + 1, col, int(re.sub('[^0-9]', '', fileLine))) found_core1 = True # 两个核心记录都找到,跳出当前文件的行循环 if found_core0 and found_core1: break # with语句会自动关闭文件,无需手动调用Probe.close() col += 1 # 每个文件处理完后再递增列,避免重复写入同一列 workbook.close()
关键修改说明
- 添加跟踪标志:每个文件初始化
found_core0和found_core1为False,确保每个文件都重新判断是否找到第一条记录 - 条件写入:只有当对应核心的标志为
False时才执行写入,避免重复处理同一核心的多条记录 - 提前终止循环:当两个核心的记录都找到后,立即
break跳出文件行循环,节省不必要的遍历 - 路径拼接优化:改用
os.path.join拼接路径,避免手动拼接出现的斜杠问题 - 语法修正:修复了
'MyFile'.xlsx的引号错误,移除了多余的Probe.close()(with上下文管理器会自动关闭文件)
这样修改后,每个日志文件只会写入Core0和Core1的第一条CPU利用率记录,不会出现重复写入的问题了。
内容的提问来源于stack exchange,提问作者Asenski
相关产品推荐
相关产品推荐

