How to read and write dictionaries to external files in python?
This question already has an answer here:
Let's create a dictionary:
>>> d = {'guitar':'Jerry', 'drums':'Mickey' }
Now, let's dump it to a file:
>>> import json
>>> json.dump(d, open('1.json', 'w'))
Now, let's read it back in:
>>> json.load(open('1.json', 'r'))
{'guitar': 'Jerry', 'drums': 'Mickey'}
Taking better care of file handles
The above illustrates the json
module but was sloppy about closing files. Better:
>>> with open('1.json', 'w') as f:
... json.dump(d, f)
...
>>> with open('1.json') as f:
... json.load(f)
...
{'guitar': 'Jerry', 'drums': 'Mickey'}
链接地址: http://www.djcxy.com/p/38054.html
上一篇: json去掉多个列表
下一篇: 如何在python中读写外部文件的字典?