How to permanently save a variable (login information)

Question:

I am trying to code a username and password system and was wondering if there was any way to save the variable so even when the code stops the username will work the next time.
I have not yet started coding it and was just wondering if this was possible. I saw a few things on saving it as a file but with no luck. Thanks!

I tried saving it as a file but, I don’t want to manually add every username and password.

Asked By: eclipz

||

Answers:

You can try appending them to a file instead of writing a new one for each user. So each time a user logs in the creds will be saved to that file. This is what I have done in the past.

Answered By: kidcoolness

You can automaticly save everything in a simple text file.

file = open("Python.txt", "w")

make sure the .txt exists and check before running that you are actually running your python file in the right directory.
Then write the variable to the file and make a newline by appending n.

file.write(str(yourVariable), "n")

Dont forget to close your file afterwards!

file.close()

To acces this varibale afterwards open it again by doing:

f = open('Python.txt', 'r')
contents= f.read()

and convert it back to your old type of variable by doing something like:

int(contents)
#or
list(contents)
Answered By: wallbloggerbeing

You are look for persistence, there are different ways to do so, python-specific option is shelve which allows you to seamlessly store dict inside file, consider following simple phone-book example, let
addphone.py content be

import shelve
name = input('What is your name?')
phone = input('What is your phone number?')
with shelve.open('phones') as db:
    db[name] = phone

and listphones.py content be

import shelve
with shelve.open('phones') as db:
    for name, phone in db.items():
        print(name,'uses phone',phone)

If your requirements stipulates interoperatibility with other software, you might consider using json or configparser, you might also consider other PersistenceTools

Answered By: Daweo
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.