I have a file called output.txt, which I want to write into from a few functions around the code, some of which are recursive. Problem is, every time I write I need to open the file again and again and then everything I wrote before is deleted. I am quite sure there is a solution, didn't find it in all questions asked here before..
def CutTable(Table, index_to_cut, atts, previousSv, allOfPrevSv):
print ('here we have:')
print atts
print index_to_cut
print Table[2]
tableColumn=0
beenHere = False
for key in atts:
with open("output.txt", "w") as f:
f.write(key)
and from another function:
def EntForAttribute(possibles,yesArr):
svs = dict()
for key in possibles:
svs[key]=(yesArr[key]/possibles[key])
for key in possibles:
with open("output.txt", "w") as f:
f.write(key)
All output I have is the last one written in one of the functions..
Every time you enter and exit the with open... block, you're reopening the file. As the other answers mention, you're overwriting the file each time. In addition to switching to an append, it's probably a good idea to swap your with and for loops so you're only opening the file once for each set of writes:
with open("output.txt", "a") as f:
for key in atts:
f.write(key)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With