Japster Japster - 3 months ago 7
Python Question

Add new data to a text file without overwriting it in python

Right, I'm running a while loop that does some calculations, and, at the end, exports the data to a .txt file. The problem is, rather than appending the data to the end of the file, it seems to overwrite it and create a brand new file instead. How would I make it append to the old file?

Here's my code:

turn = 1
while turn < times:
dip1 = randint(1,4)
dip2 = randint(1,4)
dip = (dip1 + dip2) - 2

adm1 = randint(1,4)
adm2 = randint(1,4)
adm = (adm1 + adm2) - 2

mil1 = randint(1,4)
mil2 = randint(1,4)
mil = (mil1 + mil2) - 2

with open("Monarchs Output.txt", "w") as text_file:
print("Monarch{}, adm: {}, dip: {}, mil: {}\n".format(turn, adm, dip, mil), file=text_file)

turn = turn + 1


Just to note, it runs just fine, all the required imports are at the top of the code.

Answer

Open the file before the loop starts. Every time you open the file for writing, it creates a new file (it deletes whatever is in it).

with open("Monarchs Output.txt", "w") as text_file:
    turn = 1
    while turn < times:
        dip1 = randint(1,4)
        dip2 = randint(1,4)
        dip = (dip1 + dip2) - 2

        adm1 = randint(1,4)
        adm2 = randint(1,4)
        adm = (adm1 + adm2) - 2

        mil1 = randint(1,4)
        mil2 = randint(1,4)
        mil = (mil1 + mil2) - 2

        print("Monarch{}, adm: {}, dip: {}, mil: {}\n".format(turn, adm, dip, mil), file=text_file)

        turn = turn + 1
Comments