json文件读取与修改
说白了就是一种数据转换格式,可以用来存储、传递信息的中转站,下面举个例子来了解一下:
import json
#导入json头文件
import os,sys
json_path = 'D:\\chuangxin\\test_json\\params.json'
#json原文件
json_path1 = 'D:\\chuangxin\\test_json\\param.json'
#修改json文件后保存的路径
dict={}
#用来存储数据
def get_json_data(json_path):
#获取json里面数据
with open(json_path,'rb') as f:
#定义为只读模型,并定义名称为f
params = json.load(f)
#加载json文件中的内容给params
params['batch_size'] = 16
#修改内容
print("params",params)
#打印
dict = params
#将修改后的内容保存在dict中
f.close()
#关闭json读模式
return dict
#返回dict字典内容
def write_json_data(dict):
#写入json文件
with open(json_path1,'w') as r:
#定义为写模式,名称定义为r
json.dump(dict,r)
#将dict写入名称为r的文件中
r.close()
#关闭json写模式
the_revised_dict = get_json_data(json_path)
write_json_data(the_revised_dict)
#调用两个函数,更新内容
json_path 是原文件,里面内容如下:
params {‘model_version’: ‘resnet18_distill’, ‘subset_percent’: 1.0, ‘augmentation’: ‘yes’, ‘teacher’: ‘resnext29’, ‘alpha’: 0.95, ‘temperature’: 6, ‘learning_rate’: 0.1, ‘batch_size’: 128, ‘num_epochs’: 175, ‘dropout_rate’: 0.0, ‘num_channels’: 32, ‘save_summary_steps’: 100, ‘num_workers’: 4}
但是我需要将里面的batch_size修改的小一些,并保存为json_path1
params {‘model_version’: ‘resnet18_distill’, ‘subset_percent’: 1.0, ‘augmentation’: ‘yes’, ‘teacher’: ‘resnext29’, ‘alpha’: 0.95, ‘temperature’: 6, ‘learning_rate’: 0.1, ‘batch_size’: 16, ‘num_epochs’: 175, ‘dropout_rate’: 0.0, ‘num_channels’: 32, ‘save_summary_steps’: 100, ‘num_workers’: 4}