Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How do I make a dictionary inside of a text file?

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.

like image 430
coding_n00b Avatar asked Jul 03 '11 14:07

coding_n00b


2 Answers

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.

like image 101
Roman Bodnarchuk Avatar answered Oct 06 '22 00:10

Roman Bodnarchuk


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)
like image 35
zeekay Avatar answered Oct 06 '22 00:10

zeekay