python - 如何将用户输入自动永久存储到字典中

标签 python python-3.x dictionary authentication module

users = {
    "Hi":"HM123",
    "alan": "12122",
    "12": "11"
}
def adder():
    new_user = input("Please enter user's name: ").strip()
    new_pwd = ""
    confirmer = "0"
    while new_pwd != confirmer:
        new_pwd = input("please enter a new Password: ").strip()
        confirmer = input("please confirm your password: ").strip()
        if new_pwd != confirmer:
            print("passwords does not match!!")
    users[new_user] = new_pwd
adder()

我使用字典作为用户名和密码的集合来练习创建一个简单的功能登录页面。(我将其作为模块导入到我的主文件中)。当我添加新用户和密码时,上面的代码会暂时将其添加到字典中,但是当我重新运行脚本并尝试新的用户名和密码时,它会返回不正确的用户名和密码,因为它们不在字典中。

希望找到一种方法,只需用户输入即可将新的用户名和密码永久添加到字典中,而无需自己修改字典。

最佳答案

你的字典(或多或少)存储在不稳定的 RAM 中 - 你不能(或者至少你不应该尝试)在不同的脚本运行之间保留它。

这就是人们使用数据库的原因 - 它们存储在磁盘上并且不会消失,除非发生非常糟糕的事情;)

满足您需求的最简单方法是将它们存储在单个 json 文件中。它是一种与Python字典非常相似的格式。 Python 有 json 库,允许它将此类文件解析为 python 的 dict ,反之亦然 - 将 dict 放回到文件中。

示例如下:

import json

with open("users.json", "r+") as f:
    # convert content of file users.json into users variable - it will be a dict
    users = json.load(f)

def store_to_file(users):
    with open("users.json", "w") as f:
        # save the users dict into the file users.json in json format
        json.dump(users, f, indent=4)

def adder():
    ...
    store_to_file(users)

adder()

不要忘记创建文件users.json!

{
    "Hi": "HM123",
    "alan": "12122",
    "12": "11"
}

关于python - 如何将用户输入自动永久存储到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74969048/

相关文章:

python - 用不同的开始和结束分隔符拆分字符串

python - 逻辑如何与变量赋值相结合

python - MovieWriter imagemagick 不可用

python-3.x - 使用 Python 查找 '.dng' 图像分辨率

java - 使用 map 的自定义包类不允许我从类的实例调用方法,这是关键

Python 字典理解与嵌套 for

Python Launcher 没有响应 Pygame

python - pdb绕过错误/跳转失败: can only jump from a 'line' trace event

python - 添加 undefined object

ios - 来自 JSON 的字典中的键