json数据保存和读取 配置文件

保存示例:

import json

data = {'name': 'John', 'age': 30, 'city': 'New York'}

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f)
    print("保存成功")

这个示例将 Python 字典 data 序列化为 JSON 格式,并将其写入到一个名为 data.json 的文件中。with 语句确保在写入完毕后正确地关闭文件对象。


要读取上述代码生成的 data.json 文件,可以使用 json.load() 函数将 JSON 数据加载回到 Python 对象中。示例代码如下:

读取实例

import json

with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

print(data)

运行上述代码后,会将 data.json 文件中的 JSON 数据加载回到 Python 对象 data 中,并使用 print() 函数将其打印出来。输出结果为:

{'name': 'John', 'age': 30, 'city': 'New York'}

注意,在使用 json.load() 函数加载 JSON 数据时,需要将打开文件的模式设置为只读模式('r'),因为我们只是想从文件中读取数据。如果使用可写模式('w')打开文件,则会清空文件中的内容并覆盖它,这可能会导致数据丢失

其它链接

https://www.cnblogs.com/code3/p/18426312

posted @ 2023-05-15 11:01  __username  阅读(219)  评论(0)    收藏  举报