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/