Jonah Fleming
Jonah Fleming

Reputation: 1185

How to store dictionary data over multiple uses?

I am creating a login script and I store the usernames and passwords in a dictionary. The problem is though, when I open it a second time it doesn't store the users that have already been registered. I know this is normal but is there a way to get round that? Perhaps using a file?

Here is my EDITED code:

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)

Edited results: I get through the entire script with no errors but the outfile file has nothing written on it. The dictionary still doesn't save across sessions so nothing has changed. I have changed all my sys.exit()'s to returns as well. I am using Raspian on a raspberry Pi 2 if that matters.

EDIT 2

Answered by me below :)

Upvotes: 1

Views: 109

Answers (2)

Jonah Fleming
Jonah Fleming

Reputation: 1185

Ok, by talking to someone at my school I worked out the answer. Here is the code working. Comments in the script explain:

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()

Thanks to @inspectorG4dget for giving me the tools to work on!

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113945

You are looking for a way to serialize your information. Python has the builtin cPickle library for this:

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)

Upvotes: 3

Related Questions