简体   繁体   中英

Add new lines to CSV file at each iteration in Python

I have the following code in Python. I need to execute the function dd.save() N times, each time adding some new lines to the file test.csv . My current code just overrides the content of the file N times. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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