I'm writing a program that allows the user to create a username and password. How do I write this as a dictionary into a text file, and then retrieve it when I need it? Also, if there is an easier way to do this I'm welcome to any new ideas.
Use Python serialization mechanism - pickle.
Small example:
>>> import pickle
>>> s = pickle.dumps({'username': 'admin', 'password': '123'})
>>> s
"(dp0\nS'username'\np1\nS'admin'\np2\nsS'password'\np3\nS'123'\np4\ns."
Now you can easily save content of s
to some file. After that you can read it and decode:
>>> pickle.loads(s)
{'username': 'admin', 'password': '123'}
But this approach is not quite safe. Don't use it for dangerous data or data that you rely on.
Check out "Why Python Pickle is Insecure" by Nadia Alramli.
I'd use json
. It's pretty great for that sort of thing, and in the standard library since 2.6.
import json
# write settings
with open('settings.json', 'w') as f:
f.write(json.dumps(settings))
# load settings1
with open('settings.json', 'r') as f:
settings = json.load(f)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With