因此,我正在制作一个密码生成器,并尝试将其保存到文本文件中。它是这样的:
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()
但是由于某种原因,该文本文件仅保存了最新密码。为了使此设置真正适用,我需要文本文件来保存多个密码。有什么办法可以防止这种情况?
When you are doing
open("Passwords.py", "w")
the W for write is overwriting the existing file data you can useopen("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时,将在执行write()后自动将其关闭
您正在使用写而不是附加
您输入的任何内容都会被覆盖