日志提取带等号数据列表转指定CSV格式技术求助
问题概述
需要扫描日志文件,识别包含BatchTriggerDetails关键词的行,提取键值对信息并导出为CSV格式——CSV表头对应键值对的键,每行数据对应对应的值。目前已能提取出类似['batchName=ColVal Batch', 'countOfOutboundXmlSent=183', ...]的键值对列表,但无法完成CSV格式转换。
现有实现代码
t1 = open(r"C:\Temp\tntrreporting.log", 'r') fileone = t1.readlines() text = "BatchTriggerDetails" for line in fileone: if text in (line): details_index = line.find("batchName") details_content = (line[details_index:len(line)-2]) details_1= details_content.split(",") print (details_1)
解决方案
利用Python内置的csv模块,将提取的键值对列表转换为字典后写入CSV,代码如下:
import csv # 日志文件路径 log_path = r"C:\Temp\tntrreporting.log" # 输出CSV路径 output_csv = r"C:\Temp\batch_report.csv" # 存储所有批次数据的列表 batch_data = [] text = "BatchTriggerDetails" with open(log_path, 'r') as log_file: for line in log_file: if text in line: details_index = line.find("batchName") details_content = line[details_index:len(line)-2].strip() # 分割键值对 key_value_pairs = details_content.split(",") # 转换为字典 batch_dict = {} for pair in key_value_pairs: # 处理值中包含等号的情况(如果有的话),只分割第一个等号 key, value = pair.split("=", 1) batch_dict[key.strip()] = value.strip() batch_data.append(batch_dict) # 写入CSV文件 if batch_data: # 从第一个字典获取表头 headers = batch_data[0].keys() with open(output_csv, 'w', newline='', encoding='utf-8') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=headers) writer.writeheader() writer.writerows(batch_data) print(f"CSV文件已成功导出至 {output_csv}") else: print("未找到符合条件的日志行")
关键说明
- 使用
with语句自动管理文件打开/关闭,避免资源泄漏 split("=", 1)确保值中包含等号时不会被错误分割csv.DictWriter自动处理表头和数据行的对应关系,无需手动拼接CSV内容- 增加
strip()清理键和值两端的空格,保证数据整洁
内容的提问来源于stack exchange,提问作者Akshay Hardi
相关产品推荐
相关产品推荐

