import json
# 示例数据,这是一个Python字典
data = {
"name": "Alice",
"age": 30,
"city": "Beijing",
"is_student": False,
"courses": ["Math", "Science", "Art"]
}
# 指定要写入的文件名
filename = 'data.json'
# 使用with语句打开文件,确保文件操作完成后自动关闭文件
with open(filename, 'w', encoding='utf-8') as file:
# 使用json.dump()方法将Python对象写入JSON文件
# ensure_ascii=False 确保非ASCII字符(如中文)能正确写入
# indent=4 设置缩进为4个空格,使生成的JSON文件更易读
json.dump(data, file, ensure_ascii=False, indent=4)
# 打印提示信息,表示文件写入成功
print(f"数据已成功写入 {filename}")
json 模块,用于处理JSON格式的数据。data,作为要写入JSON文件的内容。filename,指定要写入的JSON文件的名称。with open() 语句以写入模式 ('w') 打开文件,并指定编码为 utf-8,确保可以正确处理各种字符集。json.dump() 方法将Python字典 data 写入到指定的文件中。ensure_ascii=False 确保非ASCII字符(如中文)能正确写入,indent=4 设置缩进为4个空格,使生成的JSON文件更易读。这样就可以将Python字典转换为JSON格式并保存到文件中了。
上一篇:python sympy
下一篇:python pandas库用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站