如何在多种用途中存储字典数据?

时间:2015-09-16 07:14:50

标签: 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)

编辑结果 我通过整个脚本没有错误,但outfile文件没有写入任何内容。字典仍然不会跨会话保存,所以没有任何改变。我已经将所有的sys.exit()更改为return。如果重要的话,我在覆盆子Pi 2上使用Raspian。

编辑2

我在下面回答:)

2 个答案:

答案 0 :(得分:3)

您正在寻找一种序列化信息的方法。 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)

答案 1 :(得分:0)

好的,通过与我学校的某个人交谈,我找到了答案。这是代码工作。脚本中的注释说明:

import os
import sys
import pickle
#'users' dictionary stores registed users and their passwords.
status=""
users={}

#loads pickled data
def loadUsers():
    global users
    users=pickle.load(open("Dump.txt", "rb"))
#saves pickled data to Dump.txt
def saveUsers():
    global users
    pickle.dump(users, open("Dump.txt", "wb"))
#login() can register people and login.
def login():

      global users
      status=raw_input("Are you a new user y/n? Press q to quit. ")
      #creates new user by adding username and password to 'users' dictionary
      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 succesful!"
      #logs in registered users by checking for them in 'users' dictionary     
      elif status == "n":
            login=raw_input("Username: ")
            passw=raw_input("Password: ")
            if login in users and users[login] == passw:
                  print "Login successful!"
                  #opens protected app/file 
                  os.system('python Basketball\ Stats.py')
            else:
                  print "Username and password do not match!"
      #returns status to main body of script 
      return status

loadUsers()
#quit and save
try:
    while status != "q":
                    status = login()
except Exception as e:
    raise
finally:
    saveUsers()

感谢@ inspectorG4dget为我提供了工具!