【问题标题】:How do I get my program to record every victory in my game?如何让我的程序记录游戏中的每一次胜利?
【发布时间】:2014-06-27 14:15:56
【问题描述】:

这是记录胜利/失败的代码:

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()

事情是每次它记录它只是覆盖文本文件的第一行。我如何让它记录用户获得的每一次胜利/失败?

【问题讨论】:

    标签: python file-io time python-3.3


    【解决方案1】:

    事情是每次它记录它只是覆盖第一行 文本文件。

    这是因为当你打开文件时你给了模式“w”。在写入模式下,当您开始在文件中写入内容时,您会从头开始,因此新文本会替换旧文本。您需要设置附加模式“a”

    这是一个例子:

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

    我们以追加模式打开文件, 写第一行并添加一个换行符,然后写第二行,最后我们关闭文件

    【讨论】:

    • 所以像这样:vdfile = open("victorydefeat.txt", "w+a")?
    • 删除该评论。它现在可以工作,但是在写入“now”的值后如何让它开始新的一行?否则它将全部写成一条连续的线。
    • 我刚刚用一个例子更新了我的答案。我还添加了换行符来换行。如果我的回答对您有帮助,请点击我的回答左侧的勾号接受我的回答。
    猜你喜欢
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 2015-12-30
    相关资源
    最近更新 更多