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