用python替换yaml文件中的字段

时间:2017-12-19 10:35:10

标签: python yaml editing

我需要使用python代码编辑下一个yaml文件:

# This is a sample YAML file for running est.
# - Here I have the comments 1
# - Here I have comments 2


# Robust compare
# - Here I have comments 3
# - Here I have comments 4

job_name: Field1 

strategy_num: &strategy_num

dir_base   : &dir_base  high_vals

from_date_is: &from_date 20150101
to_date_is  : &to_date   20161231

# Here I have comments 5
dir: D:\Alex
run_mode      : debug

analyses:
  # Simulate for all dates (IS)
  - kind: RunStrat
    label: tr
    done: false
    dry_run: false
    from_date: *from_date
    to_date  : *to_date
    configs_to_test_dir: configs_temp

configs_to_run_dir:configs_to_run

我需要用other_high_vals替换high_vals,用other_configs_temp替换configs_temp。 我试过的一切都行不通 最后一次尝试:

def change_yaml(path_to_yaml):
    try:
        with open(path_to_yaml) as yaml_file:
            print(path_to_yaml)
            doc = yaml.safe_load(yaml_file)

        doc['dir_base'][1] = 'other_dir_base'
        doc['analyses']['configs_to_test_dir'] = other_configs_temp

    except EnvironmentError as e:
        raise ValueError('Could not open yaml file {}:\n{}'.format(path_to_yaml, e))

    try:
        with open(path_to_yaml, 'w') as yaml_file:
            yaml.dump(doc, yaml_file)
    except EnvironmentError as e:
        raise ValueError('Could not write to yaml file {}:\n{}'.format( path_to_yaml , e) 

提前谢谢

1 个答案:

答案 0 :(得分:0)

这一行:

doc['dir_base'][1] = 'other_dir_base'

假设密钥dir_base的值可以编入索引,但该值是标量high_vals,因为它在Python中作为字符串加载,所以您尝试执行以下操作:< / p>

s= 'high_vals'
s[1] = 'other_dir_base'

将提供TypeError

您可能想要这样做:

doc['dir_base'] = 'other_dir_base'