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/mubw 著作权归作者所有。请勿转载和采集!