import json
class Params():
"""Class that loads hyperparameters from a json file.
Example:
```
params = Params(json_path)
print(params.learning_rate)
params.learning_rate = 0.5 # change the value of learning_rate in params
```
"""
def __init__(self, json_path):
with open(json_path) as f:
params = json.load(f) # 将json格式数据转换为字典
self.__dict__.update(params)
def save(self, json_path):
with open(json_path, 'w') as f:
json.dump(self.__dict__, f, indent=4) # indent缩进级别进行漂亮打印
def update(self, json_path):
"""Loads parameters from json file"""
with open(json_path) as f:
params = json.load(f)
self.__dict__.update(params)
@property # Python内置的@property装饰器就是负责把一个方法变成属性调用的
def dict(self):
""
Python创建并保存json文件,支持数据更新保存
最新推荐文章于 2024-07-22 16:16:18 发布
本文介绍了如何使用Python进行JSON文件的创建、读取和更新操作。通过示例代码详细展示了如何将数据转化为JSON格式,并保存到文件中,以及如何加载文件数据并进行修改后再保存。
摘要由CSDN通过智能技术生成