coding_n00b
coding_n00b

Reputation: 61

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.

Upvotes: 5

Views: 359

Answers (4)

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29727

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.

Upvotes: 7

taskinoor
taskinoor

Reputation: 46027

>>> 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.

Upvotes: 1

Zach Kelling
Zach Kelling

Reputation: 53819

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)

Upvotes: 6

Donald Miner
Donald Miner

Reputation: 39893

Check out pickle. It is a way to serialize your objects to a file, then retrieve it.

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

Upvotes: 2

Related Questions