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?
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
>>>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments