python 读取 yaml 配置文件参数的方法

时间:2025-04-05 07:16:26
import yaml config = "test_20220105.yaml" with open(config, 'r', encoding='utf-8') as fin: configs = yaml.load(fin, Loader=yaml.FullLoader) """ 取key对应的value值的两种方式: 1、configs['key'] 2、('key') 根据下面的例子,显然第一种方式更简单。 """ # 第一级目录 max_epoch = configs['max_epoch'] # 240 max_epoch = configs.get('max_epoch') # 240 # 多级目录 max_length = configs['dataset_conf']['filter_conf']['max_length'] # 40960 max_length = configs.get('dataset_conf').get('filter_conf').get('max_length') # 40960 """ 设置默认值的方法: ('key', value) value为默认值 """ # default=100表示如果configs里面没有 max_epoch 参数,则设置 num_epochs=100;否则,取原来的值。 num_epochs = configs.get('max_epoch', 100) # 240 type = configs.get('dynamic', 'static') # static,因为 configs 中没有参数'dynamic'