سؤال

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?

هل كانت مفيدة؟

المحلول

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top