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

Python读取文本文件时如何输出触发IndexError的对应文件行号

解决方案

核心方法是使用enumerate()函数遍历文件行时同步统计行号,设置start=1参数可以让行号从1开始计数,和日常使用的文本行号习惯保持一致。

修改要点:

  • 遍历文件行列表时使用enumerate(file_rows, start=1)同时获取行号和每行内容
  • 提前将单行拆分结果存入变量,避免重复调用split()提升运行效率
  • 异常捕获块直接输出统计得到的行号即可

修改后的完整代码:

def openfile(which_file): # 打开并逐行读取所选文件的函数
    with open(which_file, "r") as file:
        file_rows = file.readlines()
        passengers = []
        # enumerate的start参数设置行号起始值为1
        for line_num, line_content in enumerate(file_rows, start=1):
            try:
                if line_content != "\n":     # 此处调用data_manager类
                    # 仅拆分一次存为变量,避免重复执行split
                    parts = line_content.split()
                    objekt = carclass.data_manager(parts[0], parts[1], parts[2], parts[9], parts[13], parts[-1])
                    passengers.append(objekt)
            except IndexError:
                # 直接输出当前统计的行号
                print(f"Wrong registration at line {line_num}")
                # 如需排查问题还可以补充输出错误行的内容:
                # print(f"错误行内容:{line_content.strip()}")
        return passengers

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:48:04