1

I'm writing something like a database, but rather simple and small. So I used a dict, which is then saved in a file.

The code is roughly:

d = {'apple': 1, 'bear': 2}
print(d, file=f)

I want it to be imported the next time I run it, i.e. import it as a dictionary from file, anyway to do it?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
YiFei
  • 1,752
  • 1
  • 18
  • 33
  • 2
    https://wiki.python.org/moin/UsingPickle – DilithiumMatrix Oct 23 '15 at 14:06
  • @DilithiumMatrix is there any way to make it readable externally with notepad or gedit? – YiFei Oct 23 '15 at 14:13
  • have you tried to open your file? is it in shape of dictionary or is it like: `apple 1 , bear 2` – user 12321 Oct 23 '15 at 14:15
  • 4
    Possible duplicate of [Python dump dict to json file](http://stackoverflow.com/questions/17043860/python-dump-dict-to-json-file) – Remi Guan Oct 23 '15 at 14:15
  • also you can use eval construction.. d = eval(open(filename, 'rb').read()) – Anton Barycheuski Oct 23 '15 at 14:18
  • @KevinGuan I'm not familiar with json files, however, if that's a good way I'd flag mine as duplicated – YiFei Oct 23 '15 at 14:19
  • or save the dict as json, if you need human-readable data (otherwise Pickle approach is better). In you simple example you can do like this: `import json; json.load(f)` – mguijarr Oct 23 '15 at 14:20
  • @AntonBarycheuski `eval()` is really dangerous. use `json.dumps()` and `json.loads()` here is the best way. – Remi Guan Oct 23 '15 at 14:20
  • @AntonBarycheuski No. Eval is completely unnecessary (not to mention potentially dangerous) – SiHa Oct 23 '15 at 14:20
  • @YiFei Well, let me post an answer with a simple example about how to use `json.dumps()`. – Remi Guan Oct 23 '15 at 14:21
  • Eval is not recommened, it is dangerous, INSTEAD, one can use literal eval with importing ast, `import ast def reading(self): s = open('file', 'r').read() self.whip = ast.literal_eval(s)` – user 12321 Oct 23 '15 at 14:22

2 Answers2

5

If you'd like save some data such as list, dict or tuple, etc. to a file. And you want to edit them or you just want them be readable . Use json module like this:

>>> import json
>>> d = {'apple': 1, 'bear': 2}

>>> print(d)
{'bear': 2, 'apple': 1}

>>> print(json.dumps(d))
{"bear": 2, "apple": 1}  # these are json data
>>> 

Now you could save these data to a file. If you want to load them, use json.loads() like this:

>>> json_data = '{"bear": 2, "apple": 1}'
>>> d = json.loads(json_data)
>>> d['bear']
2
>>>
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
1

Use literal_eval():

import ast
with open(file,'r') as f:
    for line in f.readlines():
        d = ast.literal_eval(line)
        # do things.
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
tintin
  • 3,176
  • 31
  • 34