简体   繁体   中英

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.

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

You should use open("Monarchs Output.txt", "a") instead of open("Monarchs Output.txt", "w")
link: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM