简体   繁体   中英

Replace fields in yaml file by python

I need to edit the next yaml file with python code :

# 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

I need to replace high_vals by other_high_vals and configs_temp by other_configs_temp. Everything I tried doesn't work Last try:

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) 

Thank you in advance

This line:

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

assumes that the value for the key dir_base can be indexed, but that value is the scalar high_vals and since that is loaded as a string in Python you are trying to do the equivalent of:

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

which will give a TypeError .

You probably want to do:

doc['dir_base'] = 'other_dir_base'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM