Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我如何让我的程序记录我比赛中的每一场胜利?_Python_File Io_Time_Python 3.3 - Fatal编程技术网

Python 我如何让我的程序记录我比赛中的每一场胜利?

Python 我如何让我的程序记录我比赛中的每一场胜利?,python,file-io,time,python-3.3,Python,File Io,Time,Python 3.3,以下是记录胜利/失败的代码: 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:

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

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()
问题是,每次它记录时,它只会覆盖文本文件的第一行。我如何让它记录用户获得的每一次胜利/失败

问题是每次它记录的时候,它只是覆盖了 文本文件

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

以下是一个例子:

f = open('myfile','a+')
f.write("a line\n")
f.write("a new line\n")
f.close()
我们以附加模式打开文件,
写第一行并添加一个新行字符,然后写第二行,最后我们关闭文件,如下所示:vdfile=open(“victorybealt.txt”,“w+a”)?删除该注释。它现在可以工作了,但是如何让它在“now”的值被写入之后开始一行新的内容呢?否则,它会把所有内容都写成一行。我只是用一个例子更新了我的答案。我还添加了新行字符以更改行。如果我的答案对您有帮助,请单击我答案左侧的勾号接受我的答案。