如何将特定格式日志文件转换为Pandas DataFrame并导出为CSV/Excel
日志文件转结构化表格(CSV/Excel)实现方案
需求说明
将每行XML格式的日志,提取uri、t(拆分日期和时间)、u、desc字段,转换为指定列名的DataFrame并保存为CSV/Excel文件。
实现步骤与代码
1. 依赖准备
先安装所需Python库:
pip install pandas openpyxl
pandas用于处理结构化数据openpyxl用于生成Excel文件
2. 单日志文件处理代码
import pandas as pd import xml.etree.ElementTree as ET def parse_single_log(line): # 解析单条日志的XML元素 root = ET.fromstring(line.strip()) # 提取目标属性,空值默认返回空字符串 uri = root.attrib.get('uri', '') timestamp = root.attrib.get('t', '') user = root.attrib.get('u', '') desc = root.attrib.get('desc', '') # 拆分日期和时间字段 date_str, time_str = (timestamp.split('T', 1) if 'T' in timestamp else ('', '')) return { 'uri': uri, 'Date': date_str, 'Time': time_str, 'User': user, 'Description': desc } # 替换为你的日志文件路径 log_file = "your_log_file.log" parsed_data = [] # 逐行读取并解析日志 with open(log_file, 'r', encoding='utf-8') as f: for line in f: cleaned_line = line.strip() if not cleaned_line: continue try: parsed_data.append(parse_single_log(cleaned_line)) except ET.ParseError: print(f"跳过格式无效的日志行: {cleaned_line}") # 转换为DataFrame并保存 df = pd.DataFrame(parsed_data) df.to_csv("output_logs.csv", index=False, encoding='utf-8') df.to_excel("output_logs.xlsx", index=False, engine='openpyxl') print("转换完成,文件已保存")
3. 多日志文件批量处理代码
如果需要处理目录下所有日志文件,用以下代码:
import pandas as pd import xml.etree.ElementTree as ET import os def parse_single_log(line): root = ET.fromstring(line.strip()) uri = root.attrib.get('uri', '') timestamp = root.attrib.get('t', '') user = root.attrib.get('u', '') desc = root.attrib.get('desc', '') date_str, time_str = (timestamp.split('T', 1) if 'T' in timestamp else ('', '')) return { 'uri': uri, 'Date': date_str, 'Time': time_str, 'User': user, 'Description': desc } # 替换为你的日志目录路径 log_dir = "your_log_directory" all_parsed_data = [] # 遍历目录下所有.log文件 for filename in os.listdir(log_dir): if filename.endswith('.log'): file_path = os.path.join(log_dir, filename) with open(file_path, 'r', encoding='utf-8') as f: for line in f: cleaned_line = line.strip() if not cleaned_line: continue try: all_parsed_data.append(parse_single_log(cleaned_line)) except ET.ParseError: print(f"文件 [{filename}] 中跳过无效行: {cleaned_line}") # 合并数据并保存 df = pd.DataFrame(all_parsed_data) df.to_csv("combined_logs.csv", index=False, encoding='utf-8') df.to_excel("combined_logs.xlsx", index=False, engine='openpyxl') print("所有日志文件处理完成")
4. 兼容非标准XML日志的正则方案
如果部分日志行XML格式不规范,导致解析失败,可改用正则表达式提取属性:
import re def parse_single_log_regex(line): # 正则匹配各属性值 uri = re.search(r'uri="([^"]+)"', line).group(1) if re.search(r'uri="([^"]+)"', line) else '' timestamp = re.search(r't="([^"]+)"', line).group(1) if re.search(r't="([^"]+)"', line) else '' user = re.search(r'u="([^"]+)"', line).group(1) if re.search(r'u="([^"]+)"', line) else '' desc = re.search(r'desc="([^"]+)"', line).group(1) if re.search(r'desc="([^"]+)"', line) else '' date_str, time_str = (timestamp.split('T', 1) if 'T' in timestamp else ('', '')) return { 'uri': uri, 'Date': date_str, 'Time': time_str, 'User': user, 'Description': desc }
只需将上述代码中的parse_single_log函数替换为这个即可。
注意事项
- 替换代码中的文件/目录路径为实际路径
- 若日志文件编码不是UTF-8,调整
open函数的encoding参数(如gbk) - 异常处理可根据需求扩展,比如将无效行记录到错误日志文件
内容的提问来源于stack exchange,提问作者Rejoy
相关产品推荐
相关产品推荐

