我有一个代码设置为只允许保存在文本文件中的特定用户的 3 个分数。但我正在努力完成这项工作。pname 是人名的变量,他们正确的数量存储在变量正确的下面。我还试图添加他们使用变量 etime 所花费的时间。我有基础,但无法修复错误或使这项工作,因为我试图将其从另一个答案调整到另一个问题。谢谢你。
SCORE_FILENAME = "Class1.txt"
MAX_SCORES = 3
try: scoresFile = open(SCORE_FILENAME, "r+")
except IOError: scoresFile = open(SCORE_FILENAME, "w+") # File not exists
actualScoresTable = []
for line in scoresFile:
tmp = line.strip().replace("\n","").split(",")
actualScoresTable.append({
"name": tmp[0],
"scores": tmp[1:],
})
scoresFile.close()
new = True
for index, record in enumerate( actualScoresTable ):
if record["name"] == pname:
actualScoresTable[index]["scores"].append(correct)
if len(record["scores"]) > MAX_SCORES:
actualScoresTable[index]["scores"].pop(0) # OR del actualScoresTable[index]["scores"][0]
new = False
break
if new:
actualScoresTable.append({
"name": pname,
"scores": correct,
})
scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
for record in actualScoresTable:
scoresFile.write( "%s,%s\n" % (record["name"], ","(record["scores"])) )
scoresFile.close()