How do I get multiple scores to append to the same line?

I have been set a task where I have a maths quiz that students take three times and then their scores are saved to a .txt file. The problem I am having is that, because they have to run the quiz 3 times, the ‘name’ variable gets reset every time and their scores save to three seperate lines in the text file. How can I get it so that the program recognizes if the person has played before and will there save the score to the same line within the text file?

Inside the text file created, it currently looks like this –

Tom , 10
Tom , 5
Tom , 3

How can I get it to –

Tom , 10 , 5 , 3

My quiz code:

import time

print ('What is your name?')
name = input()
print (' Hello ' + name +', Welcome to the python maths quiz, you will be asked 10 maths questions and marked out of 10 at the end, good luck! ')
time.sleep (1)
Class=input("Which class are you in? 1,2 or 3?")

import random

score = 0
for x in range (10):
    ops = ['+', '-', '*']
    num1 = random.randint(1,10)
    num2 = random.randint(1,10)
    op = random.choice(ops)
    question = '{} {} {}?'.format(num1, op, num2)
    print ('What is '+ question + '?')
    answer = input()

    if op is ("+") :
        rightanswer = num1+num2
        if answer == str(rightanswer):
            print('Well done, that is correct')
            score = score + 1
        else:
            print('Wrong, the correct answer was',rightanswer,'!')

    if op is ("-") :
        rightanswer = num1-num2    
        if answer == str(rightanswer):
            print('Well done, that is correct')
            score = score + 1
        else:
            print('Wrong, the correct answer was',rightanswer,'!')

    elif op is ("*") :
        rightanswer = num1*num2
        if answer == str(rightanswer):
            print('Well done, that is correct')
            score = score + 1
        else:
            print('Wrong, the correct answer was',rightanswer,'!')



print ("Well done " + name + "! You scored " , score,"out of 10")

if Class=="1" :
    my_file=open('Class1.txt','a')
    my_file.write(name)
    my_file.write(' , ')
    my_file.write(str(score))
    my_file.write('\n')
    my_file.close()

elif Class=="2" :
    my_file=open('Class2.txt','a')
    my_file.write(name)
    my_file.write(' , ')
    my_file.write(str(score))
    my_file.write('\n')
    my_file.close()

else :
    my_file=open('Class3.txt','a')
    my_file.write(name)
    my_file.write(' , ')
    my_file.write(str(score))
    my_file.write('\n')
    my_file.close()

Rate this post