简体   繁体   English

如何在不删除之前数据的情况下将 append 新数据放入 my.csv 文件中

[英]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.

相关问题 如何从多个 excel 文件和 append 中获取特定数据到一个新的 excel 文件中而不删除我已经使用 excel 文件?77 - How do I take specific data from multiple excel files and append it into a new excel file without deleting the data I already have with python? 如何将新数据附加到现有文件中 - how can I append the new data into existing file 如何在不删除先前循环数据的情况下使用 Pandas 创建 ForLoop? - How can I Create a ForLoop with Pandas without deleting previous loop's data? 蟒蛇 | 如何使用新行将数据附加到 csv 文件 - Python | How to append data to csv file with new line 如何将 append 的数据列表添加到 CSV 中的多个新列? - How do I append a list of data to multiple new columns in a CSV? 在 Django 模型中删除新列或删除现有表时,如何保留以前的数据? - How do I preserve previous data when deleting new columns or deleting exists table in Django models? 如何清理我的数据,以便我可以将其转换为 csv 文件 - How to clean my data, so that I can convert it into a csv file 如何使用熊猫读取csv,追加新数据以及写入新csv - how read csv, append new data, and write to a new csv with pandas csv.writer仅在csv文件中附加新数据 - csv.writer Append a csv file with new data only 在不删除先前内容的情况下将数据帧数据追加到json文件 - Appending dataframe data to a json file without deleting previous content
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM