在python中基本写入CSV文件?

时间:2017-11-17 21:18:29

标签: python python-3.x csv

我正在寻找帮助写入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()

1 个答案:

答案 0 :(得分:1)

writerow(),毫不奇怪地写了一行。因此需要将其包含在for循环中,迭代每个要写入文件的记录。