Python从fi读取和使用数据

2024-04-19 16:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将测验中的分数保存到excel表格中,这样用户就可以阅读文件了,但是我如何才能使用他们的保存数据来保存用户的最后3个分数。我明白这意味着从文件中读取分数,然后让它读取用户尝试了多少次,等等。但是我不太明白如何使它这样程序只会保存该用户的最后3个分数或他们的3个最高分数。非常感谢。在

            if pclass == 1:
                inFile = open("ascores.csv", 'a')
                inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
                inFile.close()
                inFile = open("ascores.csv", 'r')
                print(inFile.read())
            elif pclass == 2:
                inFile = open("bscores.csv", 'a')
                inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
                inFile.close()
                inFile = open("bscores.csv", 'r')
                print(inFile.read())
            elif pclass == 3:
                inFile = open("cscores.csv", 'a')
                inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
                inFile.close()
                inFile = open("cscores.csv", 'r')
                print(inFile.read(sorted(reader, key=lambda row: int(row[0]))))
            else:
                print("Sorry we can not save your data as the class you entered is 1, 2 or 3.")

Tags: csv用户closereadopen分数infilewrite
1条回答
网友
1楼 · 发布于 2024-04-19 16:22:41

在读取文件内容之前,请先关闭该文件。在

if pclass == 1:
    inFile = open("ascores.csv", 'a')
    inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
    content = inFile.read()
    inFile.close()
    inFile = open("ascores.csv", 'r')
    print(content)

或者更简洁:

^{pr2}$

使用with语句将为您关闭文件。
您可以编辑长new_score = "\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1))以:

new_score = "\n {}, {}, {:.1f}".format(pname, correct, etime)

有关字符串格式的说明,请参见:https://docs.python.org/3.4/library/string.html#format-specification-mini-language。在

你也可以简化你的代码(不要重复你自己):

def saveScore(pname, correct, etime, pclass):
    score_files = {1:"ascores.csv", 2:"bscores.csv", 3:"cscores.csv"}
    try:
        filename = score_files[pclass]
        new_score = "\n {}, {}, {:.1f}".format(pname, correct, etime)
        with open(filename, 'a') as in_file:
            in_file.write(new_score)
            content = in_file.read()         
        return content
    except KeyError:
        return None

print(saveScore(pname, correct, etime, pclass))

相关问题 更多 >