我正在尝试将测验中的分数保存到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.")
在读取文件内容之前,请先关闭该文件。在
或者更简洁:
^{pr2}$使用
with
语句将为您关闭文件。您可以编辑长
new_score = "\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1))
以:有关字符串格式的说明,请参见:https://docs.python.org/3.4/library/string.html#format-specification-mini-language。在
你也可以简化你的代码(不要重复你自己):
相关问题 更多 >
编程相关推荐