我正在寻找帮助写入python 3中的csv文件。我有下面的代码,但它似乎只写入第一行,每当我再次运行代码时它会覆盖第一行。
import csv
with open("scores1.csv", "w") as csvfile:
fieldnames = ["score", "username","topic","difficulty",]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
score = int(input("score" ))
user = input("user: ")
topic = input("topic: ")
difficulty = input("difficulty: ")
writer.writerow({"score": score, "username": user, "topic": topic, "difficulty": difficulty})
print ()
csvfile.close()
答案 0 :(得分:1)
writerow()
,毫不奇怪地写了一行。因此需要将其包含在for
循环中,迭代每个要写入文件的记录。