python-3.x 如何让我的程序正确读取文本文件?

oxiaedzo  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(126)

基本上,我试图让我的程序读取并显示同一文件夹中的一个文件(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
nbysray5

nbysray51#

the fileread function can be shortened a lot, as you can use "normal" string manipulation to do everything you're doing with your custom logic.
and just to point out what is the problem with your current logic, the file you're reading does not end with a newline character, which is very common in files.

def fileRead(filename):
    with open(filename) as infile:
        # read the whole file and split on newline characters
        data = infile.read().splitlines()
    if len(data) > 1:
        result = []
        for line in data[1:]:
            result.append(line.split())
        if len(result) > 0:
            return result
    print("invalid file")

The same goes for the other function. You're basically trying to re-invent the wheel while python has a lot of standard string/list/math things that make it a lot easier

def display(grades):
    for line in grades:
        print(" ".join(line))
        average = sum([int(grade) for grade in line]) / len(line)
        print(f"\tAverage={average:.2f}")

EDIT

to tie it into your logic, change your start function into the more pythonic dunder main magic.

if __name__ == "__main__":
    filename = input("please provide a file name:\n")
    grades = fileRead(filename)
    display(grades)

I would read up on what the so-called dunder main does, fe here

相关问题