You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将Linux traceroute输出转为CSV?遇字符拆分异常

Traceroute输出处理:转CSV或直接统计时间指标

你的代码问题分析

你之前的代码之所以会把每个字符用逗号分隔,是因为csv.writer.writerow()要求传入列表/可迭代的元素集合,而你直接传了整个字符串——字符串会被当成字符的迭代器,所以每个字符都被当成单独的列。另外直接替换空格为逗号也不合理,因为traceroute输出里的空格是不定数量的,还有带括号的IP格式需要单独处理。


方案一:转换为符合要求的CSV

下面是可以正确解析traceroute输出并生成CSV的代码,兼容丢包(* * *)的情况:

import csv

# 替换成你的输入输出文件路径
input_path = "traceroute.out"
output_path = "traceroute.csv"

with open(input_path, 'r') as infile, open(output_path, 'w', newline='') as outfile:
    csv_writer = csv.writer(outfile)
    # 可选:写入CSV表头,方便后续识别列
    csv_writer.writerow(["跳数", "IP地址", "括号内IP", "数据包1时间", "数据包2时间", "数据包3时间"])
    
    # 跳过第一行的traceroute说明信息
    next(infile)
    
    for line in infile:
        line = line.strip()
        if not line:
            continue  # 跳过空行
        
        # 按任意空白字符分割行内容,自动处理多个空格
        parts = line.split()
        hop_number = parts[0]
        ip = parts[1]
        # 可以选择去掉括号,或者直接保留原始格式
        ip_with_paren = parts[2].strip("()")
        
        # 提取三个数据包的时间,兼容丢包的*符号
        time_entries = []
        # 从第3个索引开始,每两个元素是一组(时间+ms)
        for idx in range(3, len(parts), 2):
            time_entries.append(parts[idx])
        
        # 组装一行数据并写入CSV
        csv_writer.writerow([hop_number, ip, ip_with_paren] + time_entries)

方案二:直接统计每跳的时间指标(平均值/最大值/最小值)

如果不需要生成CSV,直接对每跳的时间进行统计,用下面的代码即可:

input_path = "traceroute.out"

with open(input_path, 'r') as infile:
    # 跳过首行
    next(infile)
    
    for line in infile:
        line = line.strip()
        if not line:
            continue
        
        parts = line.split()
        hop_number = parts[0]
        ip = parts[1]
        
        # 收集可转换为数值的时间数据
        valid_times = []
        for idx in range(3, len(parts), 2):
            time_str = parts[idx]
            if time_str != "*":
                try:
                    # 转换为浮点数,方便计算
                    valid_times.append(float(time_str))
                except ValueError:
                    # 跳过无效的时间格式
                    continue
        
        # 计算并输出统计结果
        if valid_times:
            avg = sum(valid_times) / len(valid_times)
            max_t = max(valid_times)
            min_t = min(valid_times)
            print(f"跳数 {hop_number} ({ip}): 平均值={avg:.2f}ms,最大值={max_t:.2f}ms,最小值={min_t:.2f}ms")
        else:
            print(f"跳数 {hop_number} ({ip}): 无有效时间数据(全部丢包)")

内容的提问来源于stack exchange,提问作者aguywhoexiststosuffer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 12:00:32