python如何格式化写入json文件
要格式化写入JSON文件,可以使用json模块提供的dump()方法。以下是一个示例代码:
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# 打开文件,使用with语句可以自动关闭文件
with open("data.json", "w") as file:
# 使用dump()方法将数据写入文件,参数indent=4表示每个键值对缩进4个空格
json.dump(data, file, indent=4)
以上代码将字典data写入名为data.json的JSON文件中,并使用4个空格进行缩进。你可以根据需要调整缩进的空格数。
原文地址: https://www.cveoy.top/t/topic/i6dE 著作权归作者所有。请勿转载和采集!