[英]How can I append new data into my .csv file without deleting the previous data
I made a maths quiz where the program asks and stores the user's name, the question, the solution and the user's score into a.csv file.我做了一个数学测验,程序询问用户的姓名、问题、解决方案和用户的分数并将其存储到一个.csv 文件中。 My problem is that whenever the program is run the newly inputted data overwrites the previous data set, which I don't want so instead I want the new data to be appended below the old data set.
我的问题是,每当程序运行时,新输入的数据都会覆盖以前的数据集,这是我不想要的,所以我希望将新数据附加到旧数据集的下方。 How can I do this?
我怎样才能做到这一点?
Here is my code so far:到目前为止,这是我的代码:
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])
You need to open the file in append mode, like this:您需要在 append 模式下打开文件,如下所示:
with open("Quiz.csv", "a", newline="") as file:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.