1

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)
Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217
  • 1
    possible duplicate of [How do you append to a file in Python?](http://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file-in-python) – Peter Wood Mar 09 '15 at 12:21
  • 2
    You need to open in append mode so `with open("test.csv","wa") as f:` – EdChum Mar 09 '15 at 12:21

1 Answers1

4

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).

Open the file in append mode:

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

Check docs here.

Yasel
  • 2,920
  • 4
  • 40
  • 48