为什么这个 pickle 实现不起作用(即我缺少什么)

why is this pickle implementation not working(ie what am I missing)

在此代码中,我尝试使用 pickle 永久存储用户创建新帐户时创建的新用户名的值,但出现逻辑错误。并且字典中的值仍然保持不变。(我知道我在这里显然遗漏了一些明显的东西但实际上我不知道那是什么)

# defining variables
create_username = 0
create_password = 0
password = 0
username = 0

# importing pickle
import pickle

# creates a users dictionary
users = {
    'Joe': 'juk725',
    'Mat': 'axr3',
    'Th3_j0k3r': 'bl4z3',
    'ag4r-j3lly': 'Micr0b3'
}

# sign up (creating new account)
while username not in users and username != 'signup':
    username = input("enter username(type signup to create an account): ")

    # add new user to dictionary
    if username == "signup" or username == "Signup":
        create_username = input("enter a new username: ")
        create_password = input("enter a new password (Your password cannot be the same as your username !!!!!!!): ")

    if create_password in users:
        create_password = input("password taken re-enter: ")
    # then adds the new username to the users dictionary
    if username == 'signup':
        users[create_username] = create_password

    pickle.dump(users, open('pickle_file_name.p', 'wb'))



else:
    if username in users:
        password = input("enter password: ")

    if password in users:
        print("access granted")

    if username not in users:
        username = input("enter username: ")

    if password not in users:
        print("access denied")

您永远不会打开 pickled 文件,因此您的代码会重复使用相同的字典输入。

您应该只创建一个脚本来首先创建 pickle 文件,然后用 pickle.load 方法调用

替换您拥有的 users 的定义
# importing pickle
import pickle

# creates a users dictionary
with open('pickle_file_name.p', 'rb') as f:
    users = pickle.load(f)

# sign up 

如果您想要一个可读文件,我建议使用 json 模块而不是 pickle。如果想更方便的查询用户,那么sqlite3

这里也不是很相关,但是密码散列对于任何此类有帐户的项目来说都是一个好主意,而不是以明文形式存储数据