⽤python调⽤、更新json、yaml配置⽂件db_config.json⽂件
{
"host":{
"test1":"success!",
"test2":"success!"
},
python怎么读取json文件"port":120302145012
}
test_config.yaml⽂件
host:{test: Ah}
port:123456
定义获取和更新配置⽂件⽅法
# 导包
import json
import yaml
# 获取json配置⽂件
def get_json_config(file_name):
'''
input:
file_name: (str)json配置⽂件名
output:
config:(dict)json配置内容
'''
with open(file_name)as f:
config = json.load(f)
return config
# 更新json配置⽂件
def update_json_config(file_name, update_dic):
'''
input:
file_name: (str)需要更新的json配置⽂件名
update_dic: (dict)需要修改的配置内容
output:
(str)json配置⽂件更新结果
'''
try:
with open(file_name)as f:
config = json.load(f)
for key,value in update_dic.items():
config[key]= value
json.dump(config,open(file_name,'w'))
return"update json config success!"
except:
return"update json config fail!"
# 获取yaml配置⽂件
def get_yaml_config(file_name):
'''
input:
file_name: (str)yaml配置⽂件名
output:
config:(dict)yaml配置内容
'''
with open(file_name)as f:
config = yaml.load(f)
config = yaml.load(f)
return config
# 更新yaml配置⽂件
def update_yaml_config(file_name, update_dic):
'''
input:
file_name: (str)需要更新的yamln配置⽂件名
update_dic: (dict)需要修改的配置内容
output:
(str)yaml配置⽂件更新结果
'''
try:
with open(file_name)as f:
config = yaml.load(f)
for key, value in update_dic.items():
config[key]= value
yaml.dump(config,open(file_name,'w'))
return"update yaml config success!"
except:
return"update yaml config fail!"
test
db_config = get_json_config("db_config.json")
test_config = get_yaml_config("test_config.yaml")
print(db_config, test_config)
'''
输出:
{'host': {'test1': 'success!', 'test2': 'success!'}, 'port': 120302145012} {'host': {'test': 'Ah'}, 'port': 123456}
'''
update_dic ={
"port":987654321,
"user":"root",
"pwd":"123456"
}
print(update_json_config('db_config.json', update_dic))
print(update_yaml_config('test_config.yaml', update_dic))
db_config = get_json_config("db_config.json")
test_config = get_yaml_config("test_config.yaml")
print(db_config, test_config)
'''
输出:
update json config success!
update yaml config success!
{'host': {'test1': 'success!', 'test2': 'success!'}, 'port': 987654321, 'user': 'root', 'pwd': '123456'} {'host': {'test': 'Ah'}, 'port': 987654321, 'pwd': '123456', 'u ser': 'root'}
'''

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。