有可能对json
模块执行类似操作吗?
>>> import json
>>> d={1:2}
>>> json.dump(d, 'file.json')
或者,我需要先使用json.dumps
,然后使用file.write
吗?即:
>>> open('file.json', 'w').write(json.dumps(d))
试试这个方法:
import json
with open('file.json', 'w') as f:
json.dump(d, f)
解释:
在第二行中,创建并打开file.json
作为变量f。
在第三行中,您的字典d
被写入文件.json