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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.