【发布时间】:2022-01-04 21:55:34
【问题描述】:
我正在开始我的第一个项目(密码管理器)。到目前为止,我所做的就是让用户可以输入他们是否要创建新密码或查找密码。如果他们选择输入密码,密码的帐户/用途和实际密码将被保存到字典中。例如,目的可能是“yahoo”,密码是“example”。然后将该字典写在文本文件中。如果用户决定查找密码,他们所要做的就是输入密码的帐户。到目前为止一切正常,除了当我输入另一个密码和帐户时,它会覆盖预先存在的密码和帐户,而不是将新密码添加到字典中。
import json
passwords = {
}
prompt = "If you want to make a new password, type 'Make password'."
prompt += "\nIf you want to look for a password, type 'Look for password'.\n"
answer = input(prompt)
def password_list(account_name, password_name):
passwords[account_name] = password_name
answer = answer.upper()
found = 0 # used to see whether account for password can be found
if answer == "MAKE PASSWORD":
account_name = input("What use is this password for? ")
account_name = account_name.upper()
password_name = input("What is the password? ")
password_list(account_name, password_name) # purpose and password saved to dict
with open("passwords.txt", 'w+') as f:
f.write(json.dumps(passwords))
print("Your password was saved!") # dictionary gets saved to text file
elif answer == "LOOK FOR PASSWORD":
with open("passwords.txt", "r") as f:
passwords = json.loads(f.read()) # text file gets opened to read
if not passwords: # if the list is empty...
print("Sorry but there are no passwords available. Make a new one!")
elif passwords: #if the list isn't empty...
search_account = input("What account is this password for? ")
search_account = search_account.upper()
for name in passwords.keys(): # list of accounts get searched
if search_account == name: #if an account is in the dictionary
print(f"The password is '{passwords.get(name)}'.")
found = 1
break
if found != 1:
print("Sorry, we can't find such name.")
【问题讨论】:
-
你应该通过读取你的 json 文件来初始化你的密码列表(如果它在那里)。否则,当您运行
MAKE PASSWORD时,它会将新密码添加到一个空字典中,并覆盖之前可能有密码的现有密码文件。 -
另外一个不相关的提示,你不需要你的 for 循环你的密码字典。
passwords.get(search_account)将返回密码,如果它已经存储在那里,None如果没有。 -
最后,我希望这是为了学习,因为以明文形式存储密码不是最安全的方法:p
-
感谢您的回复!我没听懂,但现在我明白了问题所在。是的,这只是为了学习,所以现在只使用文本文件。
标签: python dictionary txt