简体   繁体   English

将 dict 直接转储到文件

[英]Dump dict directly to file

Is it possible to do something like this with the json module?可以用json模块做这样的事情吗?

>>> import json
>>> d={1:2}
>>> json.dump(d, 'file.json')

Or, do I need to use json.dumps and then file.write ?或者,我是否需要使用json.dumps然后file.write That is:那是:

>>> open('file.json', 'w').write(json.dumps(d))

Try this way:试试这个方法:

import json
with open('file.json', 'w') as f:
    json.dump(d, f)

Explanation:解释:

In the second line, file.json gets created and opened as the variable f.在第二行中, file.json被创建并作为变量 f 打开。

In the third line, your dictionary d gets written into the file.json在第三行,你的字典d被写入 file.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM