Python 基础教程

Python 高级教程

Python 相关应用

Python 笔记

Python FAQ

original icon
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.knowledgedict.com/tutorial/python-write-json-data-to-a-file.html

python json 数据如何写入指定文件

Python 笔记 Python 笔记


在 python 中,如何让 json 格式数据写入指定文件,其本质上是 json 形式的对象数据(如字典 dict)输出到特定文件的问题。python 中提供了 json 数据的读写 api,主要是利用标准库的 json 模块的 load 函数和 dump 函数。

数据写入文件

写入文件操作,如上所述需要用到 json 模块的 dump 函数,该函数主要序列化指定对象,参数中可以指定编码格式、缩进等设置,具体示例如下:

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

如上写法可以兼容 python 2 和 python 3。

如果是 python 3,可以支持 UTF-8、缩进等设置,更优雅的写法如下:

import json
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)