我做了一个数学测验,程序询问并将用户名、问题、答案和用户的分数存储到.csv文件中。我的问题是,每当程序运行时,新输入的数据都会覆盖以前的数据集,我不希望这样,所以我希望新数据附加在旧数据集的下面。我该怎么做?
这是我到目前为止的代码:
import csv
import random
Name = input("Enter your name: ")
score = 0
a = random.randint(1,100)
b = random.randint(1,100)
Q1 = int(input(str(a) + " + " + str(b) + " = "))
A1 = a + b
x = random.randint(1,100)
y = random.randint(1,100)
Q2 = int(input(str(x) + " - " + str(y) + " = "))
A2 = x - y
if Q1 == A1:
score1 = score + 1
else:
score1 = score
if Q2 == A2:
score2 = score + 1
else:
score2 = score
with open("Quiz.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow([Name, "Question", "Solution", "Mark"])
writer.writerow([1, str(a) + " + " + str(b) , A1, score1])
writer.writerow([2, str(x) + " - " + str(y) , A2, score2])
您需要以附加模式打开文件,如下所示:
with open("Quiz.csv", "a", newline="") as file: