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

4
  • open file in append mode. open("output.txt", "a") Commented Nov 13, 2015 at 13:17
  • pass f around or make it global Commented Nov 13, 2015 at 13:17
  • 1
    When I'm doing something like this that initially requires one write then a lot of appends, I usually do something like this: with open('file.txt', 'w' if not os.path.isfile('file.txt') else 'a') as f: Commented Nov 13, 2015 at 13:20
  • 2
    @Tgsmith61591 How does that function differently from open('file.txt', 'a')? Commented Nov 13, 2015 at 13:24

4 Answers 4

9

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)
Sign up to request clarification or add additional context in comments.

Comments

5

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:

Comments

3

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?

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.