【问题标题】:Dictionary is being overwritten with new input字典被新输入覆盖
【发布时间】: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


【解决方案1】:

很酷的项目。

这是因为每次启动脚本时都会强制密码 dic 为空。因此,当您添加密码时,它会添加到一个新的空 dic 中,然后您会用这个空 dic + new_password 覆盖文件。

编写代码时,请考虑每次运行时最可能的结果:文件存在。如果没有,则创建它。

这就是我在load_passwords() 函数中演示的内容。

另外,我向您建议一种更 Pythonic(和高效)的方式来搜索字典的键,时间为 O(1) 而不是 O(n)。

import json

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

def load_passwords():
    try:
        with open("passwords.txt", "r") as f:
            passwords = json.loads(f.read()) # text file gets opened to read
        return passwords
    except FileNotFoundError:
        print("Sorry but there are no passwords available. Make a new one!")
        return {}

def password_list(account_name, password_name):
    passwords = load_passwords()
    passwords[account_name] = password_name
    return passwords

if answer == "MAKE PASSWORD":
    account_name = input("What use is this password for? ").upper()
    password_name = input("What is the password? ")
    passwords = 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":
        passwords = load_passwords()

        if passwords:  #if the list isn't empty...
            search_account = input("What account is this password for? ").upper()

            # this is much better
            if search_account in passwords:
                print(f"The password is '{passwords.get(search_account)}'.")
            else:
                print("Sorry, we can't find such name.")

注意:请务必在保存到文件之前加密您的密码。

【讨论】:

  • 啊,你看这更有意义。还在学习python的来龙去脉,不过谢谢!我会离开这个。
【解决方案2】:

“你可能应该通过读取你的 json 文件来初始化你的密码列表(如果它在那里)。否则,当你运行 MAKE PASSWORD 时,它会将新密码添加到一个空字典并覆盖可能有密码的现有密码文件之前在里面。” --rchome

【讨论】:

    猜你喜欢
    • 2018-02-05
    • 1970-01-01
    • 2018-12-21
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多