-2

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

01F0
  • 1,228
  • 2
  • 19
  • 32
aviadm71
  • 53
  • 1
  • 9

4 Answers4

4

You need to change the second flag when opening the file:

  • w for only writing (an existing file with the same name will be erased)
  • a opens the file for appending

Your code then should be:

with open("output.txt", "a") as f:
Javitronxo
  • 817
  • 6
  • 9
2

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)
glibdud
  • 7,550
  • 4
  • 27
  • 37
2

I believe you need to open the file in append mode (as answered here: append to file in python) like this:

with open("output.txt", "a") as f:
    ## Write out
TayTay
  • 6,882
  • 4
  • 44
  • 65
0

Short answer. change the 'w' in the file descriptor to 'a' for append.

with open("test.txt", "a") as myfile:
    myfile.write("appended text")

this has already been answered in this thread. How do you append to a file?

Community
  • 1
  • 1
Thom
  • 540
  • 5
  • 12