终止代码后,为什么文本文件不保存写入的内容? [重复]

因此,我正在制作一个密码生成器,并尝试将其保存到文本文件中。它是这样的:

import string
from random import *

characters = string.ascii_letters + string.punctuation  + string.digits
password =  ("".join(choice(characters) for x in range(randint(8, 16))))
print(password)

choice = input("What is your password for?")
F = open("Passwords.py", "w")
F.write("\n" + choice + ": " + password)
F.close()

但是由于某种原因,该文本文件仅保存了最新密码。为了使此设置真正适用,我需要文本文件来保存多个密码。有什么办法可以防止这种情况?

评论
  • lsunt
    lsunt 回复

    When you are doing open("Passwords.py", "w") the W for write is overwriting the existing file data you can use open("Passwords.py", "a") to append data to the file and this will add you new password without overwriting the existing.
    You can do as following

    with open("Passwords.py", "a") as f:
        f.write("\n" + choice + ": " + password)
    

    在文件上使用with时,将在执行write()后自动将其关闭

  • 若相惜
    若相惜 回复

    您正在使用写而不是附加

    您输入的任何内容都会被覆盖

    F = open("passwords.txt", "a")
    f.append("/n" + choice + ": " + password)