I'm creating a program in Python 3.x where a quiz containing randomly generated simple arithmetic questions (e.g. 3 x 8). The quiz will be played by 3 different classes of school students (not real ones!), and the latest 3 scores of each student should be stored. The scores for each class should be kept separately (in 3 text files).
After the quiz is played by a student, the student's score for that try should be added to their scores.
I created the following code, where filename
is the name of the text file which stores the student's class' scores, score
is the student's score that they just acheived, fullName
is the student's full name (which they inputted at the start), and scores
is a dictionary which stores the user's class' 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
But when I run it, I receive an error:
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
I thought that this was because the text files were empty, so when the program tried to read from them, it produced an error. So, I changed it to this:
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
But when I run the program multiple times, either with different names or with the same name, only the score from the newest try appears. I tried having data already in a text file and then running the program without the try...except
statement, but the same SyntaxError
still occurred. Why is this happening? Please note that I am a beginner, though, so I may not understand a lot of things.