I have a basic login program which accepts usernames and corresponding passwords from the user. I found that even if we append the data to a list or add to a dictionary, it gets erased as soon as we close the program. What I want is a way to store this data in more permanent way so that I can access it again when I restart the program.
I have tried using text files as a permanent storage space but the program often throws errors. I want to have a more efficient and powerful way to store the data.
Any suggestions are welcome, but I would prefer if they used standard modules, if modules are to be used at all.
You might try a shelve
, which is essentially a keyed pickle. That has some advantages, in particular you don't need to read in the whole set (although we don't know how many you intend to store). Here is an example for Python 2:
First create your shelve, for example:
import shelve
db = shelve.open('passwd')
db['user1'] = 'password'
db['user2'] = 'mummble'
db['root'] = 'secret'
db.close()
Now test it:
import shelve
import getpass
db = shelve.open('passwd')
uname = raw_input("Username: ")
passw = getpass.getpass("Password: ")
if uname in db and db[uname] == passw:
print "Login Sucessful!"
else:
print "Invalid Username or Password"
db.close()
As I said in my comments, this stores passwords as plain text and is a security risk, but that does not appear to be an issue here. Otherwise, look at the hashlib
module in the standard library.
The shelve
can be used as if it was a dictionary, but it actually uses a small basic database (you should see a file called passwd.db
depending on the OS). Note I am using getpass
which is a standard library module specifically for getting passwords. You could use raw_input
if you are not bothered about hiding the password.