python - 如何存储多次使用的字典数据?

标签 python dictionary memory

我正在创建一个登录脚本,并将用户名和密码存储在字典中。问题是,当我第二次打开它时,它不会存储已经注册的用户。我知道这是正常的,但有什么办法可以解决这个问题吗?也许使用文件?

这是我编辑的代码:

import os
import sys
users={}
status=""

def login():
    status=raw_input("Are you a new user?")
    if status=="y"
        createnewuser=raw_input("Create username: ")
        if createnewuser in users:
            print "User already exists!"
        else createpsswrd=raw_input("Create new password")
            users[createnewuser]=createpsswrd 
            print "Register successful!"
    elif status == "n":
        login=raw_input("Username: ")
        passw=raw_input("Password: ")
        if login in users and users[login]==passw:
            print "Login successful!"
            os.system("python file.py")
            return
        else:
            print "Username and password do not match."
try:
    with open('file') as infile:
        cPickle.load(infile)
except:
    users = {}

while status != "q":
    login()

with open('file') as outfile:
    cPickle.dump(users, outfile)

编辑结果: 我顺利完成了整个脚本,但输出文件文件上没有写入任何内容。字典仍然不会跨 session 保存,因此没有任何变化。我也将所有 sys.exit() 更改为返回。如果重要的话,我正在树莓派 2 上使用 Raspian。

编辑2

下面是我的回答:)

最佳答案

您正在寻找一种方法来序列化您的信息。 Python 有内置的 cPickle库:

import cPickle

try:
    with open('/path/to/file') as infile:
        users = cPickle.load(infile)
except:
    users = {}

while status != "q":
    login()

with open('/path/to/file', 'w') as outfile:
    cPickle.dump(users, outfile)

关于python - 如何存储多次使用的字典数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32602019/

相关文章:

Java泛化方法来验证对象参数中的空值

python - 如何根据 Pandas DataFrame 中其他列的值仅对列的某些元素求和?

Pythonic 和紧凑的方式来比较字典中的键

r - 在巨大矩阵上应用运算时不允许使用负长度向量

python - python在哪里保存最后一次操作的结果?

python - Python 3 中更简单的文本菜单

python - 读取带有德语字符的 json 文件 python 2 (ironpython)

无法确定神秘段错误的原因

c++ - 指针内存分配

python - 如何正确解码 RTF 中的十六进制值