我在Python 3.x中创建一个程序,其中包含随机生成的简单算术问题(例如3 x 8)的测验。测验将由3个不同类别的学生(不是真正的学生)进行,并且应该存储每个学生的最新3个分数。每个班级的分数应分开保存(在3个文本文件中)。
在学生参加测验后,应将学生在该项考试中的分数添加到他们的分数中。
我创建了以下代码,其中filename
是存储学生课程的文本文件的名称'分数,score
是他们刚刚获得的学生分数,fullName
是学生的全名(他们在开始时输入),而scores
是一个存储用户班级的字典'分数:
with open(filename, "a+") as file:
scores = ast.literal_eval(file.read())
#loads student's class' scores into dict
if fullName not in scores:
scores[fullName] = collections.deque(maxlen=3)
#adds key for student if they haven't played before
scores[fullName].append(score)
#adds student's new score to their scores
with open(filename, "w") as file:
file.write(str(scores))
#writes updated class scores to student's class' file
但是当我运行它时,我收到一个错误:
Traceback (most recent call last):
File "E:\My Documents\Quiz.py", line 175, in <module>
menu()
File "E:\My Documents\Quiz.py", line 142, in menu
scores = ast.literal_eval(file.read())
File "C:\Python34\lib\ast.py", line 46, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "C:\Python34\lib\ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 0
^
SyntaxError: unexpected EOF while parsing
我认为这是因为文本文件是空的,所以当程序试图从它们读取时,它会产生错误。所以,我改为:
with open(filename, "a+") as file:
try:
scores = ast.literal_eval(file.read())
except SyntaxError:
scores = {}
#loads student's class' scores into dict, but if
#text file is empty, it creates empty dict by itself.
if fullName not in scores:
scores[fullName] = collections.deque(maxlen=3)
#adds key for student if they haven't played before
scores[fullName].append(score)
#adds student's new score to their scores
with open(filename, "w") as file:
file.write(str(scores))
#writes updated class scores to student's class' file
但是当我多次运行程序时,无论是使用不同的名称还是使用相同的名称,只会显示最新尝试的分数。我尝试将数据放在文本文件中,然后在没有try...except
语句的情况下运行程序,但仍然发生了相同的SyntaxError
。为什么会这样?请注意,我是初学者,所以我可能不了解很多东西。
答案 0 :(得分:1)
您可以使用 deque 和 pickle ,但为了简单起见,我们将使用json转储dict,使用list来保存值:
# Unless first run for class we should be able to load the dict.
try:
with open(filename, "r") as f:
scores = json.load(f)
except FileNotFoundError:
scores = {}
# game logic where you get score...
# try get users list of scores or create new list if it is their first go.
student_list = scores.get(fullName, [])
# if the user has three score remove the oldest and add the new.
# student_list[1:] takes all but the first/oldest score.
if len(student_list) == 3:
scores[fullName] = student_list[1:] + [score]
else:
# else < 3 so just append the new score.
student_list.append(score)
scores[fullName] = student_list
# dump dict to file.
with open(filename, "w") as f:
json.dump(scores, f)