Reputation: 16050
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)
Upvotes: 1
Views: 2182
Reputation: 3120
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.
Upvotes: 4