Python从文件中读取和使用数据

时间:2015-01-26 11:03:54

标签: 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.")

1 个答案:

答案 0 :(得分:0)

您正在关闭文件,然后才能阅读其内容。

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)

或更简洁:

if pclass == 1:
    new_score = "\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1))
    with open("ascores.csv", 'a') as in_file:
        in_file.write(new_score)
        content = in_file.read()
    print(content)

使用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))