Python - How to make a dictionary inside a text file?

I am writing a program that allows a user to create a username and password. How to write this as a dictionary into a text file and then get it when I need it? In addition, if there is an easier way to do this, I will be happy with any new ideas.

+5
source share
4 answers

Use Python serialization engine - pickle .

A 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 the contents sto some file. After that you can read and decode:

>>> pickle.loads(s)
{'username': 'admin', 'password': '123'}

. , .

" Python Pickle " .

+7

json. , 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)
+6

Check out pickle . This is a way to serialize your objects to a file and then get it.

Also check the shelve , which will give you a more abstract feeling for serialization.

+2
source
>>> f = open('pass_file','w')
>>> d = {"name":"my_name", "pass":"my_pass"}
>>> import pickle
>>> pickle.dump(d, f)
>>> f.close()


>>> import pickle
>>> f = open('pass_file', 'r')
>>> d = pickle.load(f)
>>> d
{'name': 'my_name', 'pass': 'my_pass'}
>>>

And there is a faster version called cPickle .

+1
source

All Articles