简体   繁体   English

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

[英]Add new lines to CSV file at each iteration in Python

I have the following code in Python. 我在Python中有以下代码。 I need to execute the function dd.save() N times, each time adding some new lines to the file test.csv . 我需要执行Ndd.save()函数,每次将新行添加到文件test.csv My current code just overrides the content of the file N times. 我当前的代码仅覆盖N次文件内容。 How can I fix this issue? 如何解决此问题?

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)

Open the file in append mode: 以追加模式打开文件:

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

Check docs here . 在此处检查文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM