python json写入
Python中使用json
模块来进行JSON数据的读写操作,以下是写入JSON数据的示例代码:
import json
# 定义要写入的JSON数据
data = {
"name": "Tom",
"age": 18,
"gender": "male"
}
# 将JSON数据写入文件
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
在上面的代码中,我们首先定义了一个包含三个键值对的字典data
,然后使用open()
函数打开一个名为data.json
的文件,打开方式为写入模式(w
)。然后使用json.dump()
函数将data
字典中的数据写入文件中。ensure_ascii=False
参数表示不对非ASCII字符进行转义,indent=4
参数表示每个数据项缩进4个空格,以提高可读性。
写入JSON数据的过程比较简单,只需要使用json.dump()
函数即可。
原文地址: http://www.cveoy.top/t/topic/J1o 著作权归作者所有。请勿转载和采集!