自学内容网 自学内容网

python读写json文件详解

在Python中,可以使用json模块来读写JSON格式的文件。下面是一个详细的示例,演示了如何读写JSON文件:

import json

# 写入JSON文件
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

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

# 读取JSON文件
with open('data.json', 'r') as f:
    loaded_data = json.load(f)
    print(loaded_data)

在这个示例中,首先定义了一个字典data,然后使用json.dump将数据写入到名为data.json的文件中。接着使用json.load读取data.json文件,并将读取的数据加载到loaded_data变量中,最后打印出加载的数据。


原文地址:https://blog.csdn.net/yongzhouchen/article/details/136507873

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!