【问题标题】:How to store dictionary data over multiple uses?如何存储多种用途的字典数据?
【发布时间】:2015-12-12 15:38:25
【问题描述】:

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

这是我的编辑代码:

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)

编辑结果: 我通过整个脚本没有任何错误,但输出文件上没有任何内容。字典仍然没有跨会话保存,所以没有任何改变。我也将所有 sys.exit() 更改为返回。如果这很重要,我会在树莓派 2 上使用 Raspian。

编辑 2

下面由我回答:)

【问题讨论】:

  • 您必须在每次运行时序列化和重新加载数据。看看docs,尤其是pickle模块。
  • 另外,杀死sys.exit()。这将抛弃您以后提出的任何外部程序流程。使用return 来突破函数,而不是

标签: python dictionary memory


【解决方案1】:

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

【讨论】:

  • 我假设“文件路径”是我上面写的原始文件?
  • @JonahFleming:不!这是您要保存数据的文件
  • 所以我把它写在我的原始文件中?
  • 是的。用我的代码替换 login() 的 while 循环
  • 它不起作用。没有任何内容写入我指定的文件。也没有错误。
【解决方案2】:

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

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 为我提供了工作工具!

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多