字典正在被新输入覆盖

Dictionary is being overwritten with new input

我正在开始我的第一个项目(密码管理器)。到目前为止我所做的是让用户可以输入他们是想创建一个新密码还是寻找一个密码。如果他们选择输入密码,则密码的 account/purpose 和实际密码将保存到字典中。例如,目的可以是“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 时,它会将新密码添加到一个空的字典中并覆盖现有的密码文件,以前可能有密码。” – rchome

很棒的项目。

这是因为每次启动脚本时都会强制密码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.")

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