我有一个代码设置为只允许来自特定用户的3个分数保存在文本文件中。但我正在努力完成这项工作。 pname是人员名称的变量,他们正确的数量存储在正确的变量下。我也试图增加他们使用变量etime所花费的时间。我有基础,但无法修复错误或使这项工作,因为我试图从另一个答案适应不同的问题。 谢谢。所有的Python保存到有限制的文件
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()
我认为你的问题会受益于简化。 – 2015-02-09 12:14:44
这是用于[GCSE计算编程任务(14 - 16岁)](http://www.reddit.com/r/Python/comments/2gawvg/gcse_computing_programming_tasks_14_16_year_olds/)? – 2015-02-09 12:16:35
它是我班上唯一一个这样做的。并且是该国6%的一部分。我挣扎着。即使我的老师也无法帮助我,因为他们对Python也不太了解。那么有人可以帮忙吗?我只是试图让它保存变量:pname,正确和etime(人名,他们得到的权利和他们花费的时间),所以我想它看起来像这样: – PythonBeginner 2015-02-09 13:20:38