简体   繁体   English

字典被新输入覆盖

[英]Dictionary is being overwritten with new input

I'm starting my first project (a password manager).我正在开始我的第一个项目(密码管理器)。 What I have done so far is make it so the user can input whether they want to make a new password or look for a password.到目前为止,我所做的就是让用户可以输入他们是否要创建新密码或查找密码。 If they choose to enter a password, the account/purpose for the password and the actual password will be saved to a dictionary.如果他们选择输入密码,密码的帐户/用途和实际密码将被保存到字典中。 For example, a purpose could be for "yahoo" and the password being "example".例如,目的可能是“yahoo”,密码是“example”。 That dictionary is then written down in a text file.然后将该字典写在文本文件中。 If the user decides to look for a password, all they would have to do is type in the account for the password.如果用户决定查找密码,他们所要做的就是输入密码的帐户。 So far everything is working except for the fact that when I enter another password and account, it overwrites the pre-existing password and account instead of adding the new password to the dictionary.到目前为止,一切正常,除了当我输入另一个密码和帐户时,它会覆盖预先存在的密码和帐户,而不是将新密码添加到字典中。

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.")

"You should probably initialize your password list by reading your json file if it's there. Otherwise, when you run MAKE PASSWORD, it adds the new password to an empty dict and overwrites the existing password file which might've had a password in there before." “您可能应该通过读取 json 文件(如果存在)来初始化您的密码列表。否则,当您运行 MAKE PASSWORD 时,它会将新密码添加到空字典并覆盖现有密码文件,该文件之前可能有密码。” – rchome – rchome

Cool project.很酷的项目。

It's because every time you start the script you force the password dic to be empty.这是因为每次启动脚本时都会强制密码 dic 为空。 So when you add a password, it's added to a new empty dic and than you overwrite the file with this empty dic + new_password.因此,当您添加密码时,它会被添加到一个新的空 dic 中,然后用这个空 dic + new_password 覆盖文件。

When you code, think about the most likely outcome at every run: the file exists.编写代码时,请考虑每次运行时最可能的结果:文件存在。 IF it doesn't, than create it.如果没有,则创建它。

This is what I demonstrate here in the load_passwords() function.这就是我在load_passwords() function 中演示的内容。

As an extra, I propose to you a more Pythonic (and efficient) way to search through a dictionary's keys in O(1) rather than O(n).另外,我向您建议一种更 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.")

Note: Be sure to encrypt your passwords before saving to a file.注意:确保在保存到文件之前加密您的密码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM