Python如何批量提取日志时间戳并按指定格式写入Excel
问题背景
Python初学者需要从本地运行日志中提取带指定特征的时间戳,按格式要求写入Excel表格,当前实现存在两个核心卡点:
- 仅能提取到单条Boot类型的时间戳,无法归集日志中所有匹配到的目标值
- 提取的时间戳无法满足指定的格式规范
现有代码存在的具体问题
- 单元格坐标写死:匹配到目标模式时永远固定写入索引为1的行位置,后匹配到的同类型数据会直接覆盖之前的结果,无法存储全量匹配值
- 变量无累计逻辑:每次循环匹配时变量被重置,没有针对不同匹配类型做行位置的动态累计
- 基础语法疏漏:存在字符串引号未闭合、xlwt工作表创建方法拼写错误的问题,代码无法正常运行
- 时间戳提取逻辑粗糙:直接截取字符串前13位,未预处理行内容,容易带入多余的空白、转义字符,不符合格式要求
可落地的修正方案
- 为每类需要提取的匹配模式单独配置独立的行计数器,计数器初始值设为1(对应Excel表头下的第一行数据),每成功匹配到一条对应模式的行,就将时间戳写入计数器指向的单元格,随后计数器自增,从根源上避免数据覆盖
- 逐行读取日志时先对行内容做去首尾空白的预处理,再截取时间戳字段,保证提取的时间值格式纯净符合要求
- 根据匹配模式的归属,动态写入对应列的单元格位置,不需要提前写死坐标
修正后的可直接运行代码
import xlwt # 定义需要匹配的日志特征 pat1 = 'Boot 0x0100M' pat2 = '2Sync:0 4' pat3 = '2Sync:1 C' pattern_list = [pat1, pat2, pat3] # 初始化Excel工作簿 book = xlwt.Workbook(encoding='utf-8') sheet1 = book.add_sheet("Sheet1", cell_overwrite_ok=True) # 写入表头 sheet1.write(0, 0, "spin") sheet1.write(0, 1, "start") sheet1.write(0, 2, "end") # 预填充spin序号列 count = 0 for i in range(1, 9): sheet1.write(i, 0, count) count += 1 # 为每类匹配结果配置独立的写入行计数器 boot_row_index = 1 # Boot时间戳的起始写入行 sync0_row_index = 1 # 2Sync:0类型结果的起始写入行 sync1_row_index = 1 # 2Sync:1类型结果的起始写入行 # 逐行读取日志文件 with open('C:\\Test_Automation\\spinup_spindown.txt', encoding='utf-8') as log_file: for raw_line in log_file: # 预处理:去除行首尾的空白、换行符 cleaned_line = raw_line.strip() # 逐特征匹配 for pattern in pattern_list: if pattern in cleaned_line: # 截取前13位作为标准格式时间戳 timestamp = cleaned_line[0:13] # 按特征类型写入对应单元格,写完后行号自增 if pattern == pat1: sheet1.write(boot_row_index, 1, timestamp) boot_row_index += 1 if pattern == pat2: sheet1.write(sync0_row_index, 2, timestamp) sync0_row_index += 1 if pattern == pat3: sheet1.write(sync1_row_index, 2, timestamp) sync1_row_index += 1 # 保存Excel文件 book.save("C:\\Test_Automation\\trial.xls")
内容的提问来源于stack exchange,提问作者programmersblock
相关产品推荐
相关产品推荐

