将dict直接转储到文件中



有可能对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

最新更新