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

Python读取grades.txt触发IndexError,如何正确读取文本文件?

Python读取grades.txt触发IndexError问题排查

我尝试编写Python程序读取同目录下grades.txt中的成绩列表并展示,但无论调整文件路径、读取参数或读取流程,始终触发IndexError。以下是相关代码、报错信息及grades.txt内容:

原始代码

END_OF_LINE = ""
EMPTY = ""
NEWLINE = "\n"
SPACE = " "


def display(grades, numRows, numColumns):
    currentRow = 0
    currentColumn = 0
    total = 0
    average = 0
    while (currentRow < numRows):
        total = 0
        average = 0
        currentColumn = 0
        while (currentColumn < numColumns):
            print("%s" % grades[currentRow][currentColumn], end=SPACE)
            total = total + int(grades[currentRow][currentColumn])
            currentColumn = currentColumn + 1
        average = total / numColumns
        print("\tAverage=%.2f" % (average))
        currentRow = currentRow + 1


def fileRead():
    fileOK = False
    grades = []
    maxColumns = 0
    while (fileOK == False):
        try:
            filename = input("Name of input file: ")
            inputfile = open(filename, "r")
            fileOK = True
            aLine = inputfile.readline()
            if (aLine == EMPTY):
                print("%s is an empty file")
            else:
                aLine = inputfile.readline()
                currentRow = 0
                while (aLine != END_OF_LINE):
                    currentCharacter = 0
                    grades.append([])
                    while (aLine[currentCharacter] != NEWLINE):
                        # Only add grades not spaces to the list of grade points
                        if (aLine[currentCharacter] != SPACE):
                            grades[currentRow].append(aLine[currentCharacter])
                        currentCharacter = currentCharacter + 1
                    currentRow = currentRow + 1
                    aLine = inputfile.readline()
                inputfile.close()
        except IOError:
            print("Problem reading from file %s" % (filename))
            fileOK = False
    numRows = currentRow
    numColumns = len(grades[0])
    return (grades, numRows, numColumns)


def start():
    grades, numRows, numColumns = fileRead()
    display(grades, numRows, numColumns)


start()

报错信息

Name of input file: grades.txt
Traceback (most recent call last):
  File "C:", line 68, in <module>
    start()
  File "C:", line 64, in start
    grades, numRows, numColumns = fileRead()
  File "C:", line 47, in fileRead
    while (aLine[currentCharacter] != NEWLINE):
IndexError: string index out of range

grades.txt内容

Spring 2020 Grades for CPSC 217 Lecture
4 4 3 2 0
4 4 4 4 3

问题原因

  1. 行末无换行符触发越界:readline()读取文件最后一行时,返回的字符串末尾没有\n,循环while (aLine[currentCharacter] != NEWLINE)会持续递增currentCharacter,直到超出字符串长度,触发IndexError。
  2. 冗余读取导致逻辑异常:读取文件时,先读取了标题行,紧接着又调用一次readline(),若文件只有标题行,后续逻辑会处理空行引发问题。
  3. 逐字符处理效率低且易出错:手动逐个字符判断空格的方式容错性差,不如直接用字符串分割方法处理成绩数据。

修复后的代码

def display(grades, numRows, numColumns):
    for row in grades:
        total = sum(int(grade) for grade in row)
        average = total / numColumns
        print(" ".join(row), end="\t")
        print(f"Average={average:.2f}")


def fileRead():
    while True:
        try:
            filename = input("Name of input file: ")
            with open(filename, "r") as inputfile:
                # 跳过标题行
                next(inputfile)
                grades = []
                for line in inputfile:
                    line = line.strip()
                    if not line:
                        continue
                    # 按空格分割成绩,自动忽略多余空格
                    row_grades = line.split()
                    grades.append(row_grades)
                if not grades:
                    print("文件中没有有效成绩数据")
                    continue
                numRows = len(grades)
                numColumns = len(grades[0])
                return grades, numRows, numColumns
        except IOError:
            print(f"读取文件 {filename} 失败,请重试")


def start():
    grades, numRows, numColumns = fileRead()
    display(grades, numRows, numColumns)


start()

修复说明

  • 用with语句自动管理文件资源,无需手动关闭文件,避免资源泄漏。
  • 用next(inputfile)直接跳过标题行,逻辑更简洁。
  • 利用strip()去除行首尾空白、split()按空格分割成绩,替代低效的逐字符判断,同时自动处理多个连续空格的情况。
  • 增加空行判断,跳过文件中的无效空行。
  • 替换while循环为for循环,代码更易读、维护性更强。
  • 使用f-string格式化输出,语法更直观简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 16:05:22