Search code examples
pythonvariablespasswordssave

How to permanently save a variable (login information)


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.


Solution

  • 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