Question

Here's the code for recording victory/defeat:

def guessingTime(answer):
    vdfile = open("victorydefeat.txt", "w")
    now = time.asctime(time.localtime(time.time()))
    print("That's 20! Time to guess.\n")
    guess = input("Is it a(n): ")
    if guess.lower() == answer:
        print("You got it! Congratulations!")
        vdfile.write("Victory achieved on ")
        vdfile.write(now)
    else:
        print("Sorry, but the answer was", answer)
        vdfile.write("Defeated on ")
        vdfile.write(now)
    vdfile.close()

Thing is every time it records it just overwrites the first line of the text file. How do I get it to record every victory/defeat the user gets?

Was it helpful?

Solution

Thing is every time it records it just overwrites the first line of the text file.

This is happening because when you open the file you gave mode "w". On write mode, when you start writing something in the file you start from the beginning, as a result the new text replaces the old one. You need to set append mode "a"

Here is an example:

f = open('myfile','a+')
f.write("a line\n")
f.write("a new line\n")
f.close()

We open the file in append mode, write the first line and add a new line character , then write second line , finally we close the file

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top