在 Python 的每次迭代中向 CSV 文件添加新行

Add new lines to CSV file at each iteration in Python

我在Python中有以下代码。我需要执行函数 dd.save() N 次,每次都向文件 test.csv 添加一些新行。我当前的代码只是覆盖了文件内容 N 次。我该如何解决这个问题?

def save(self):  

    f = csv.writer(open("test.csv", "w"))

    with open("test.csv","w") as f:
        f.write("name\n")
        for k, v in tripo.items():
            if v:
                f.write("{}\n".format(k.split(".")[0]))
                f.write("\n".join([s.split(".")[0] for s in v])+"\n")


if __name__ == "__main__":
    path="data/allData"

    entries=os.listdir(path)

    for i in entries:
      dd=check(dataPath=path,entry=i)
      dd.save()
      print(i)

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position).

以附加模式打开文件:

with open("test.csv","a") as f:
        f.write("name\n")

检查文档 here