繁体   English   中英

用python替换yaml文件中的字段

[英]Replace fields in yaml file by python

我需要使用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) 

先感谢您

这行:

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

假定键dir_base的值可以被索引,但是该值是标量high_vals并且由于该值在Python中作为字符串加载,因此您尝试执行以下操作:

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

这将给出TypeError

您可能想做:

doc['dir_base'] = 'other_dir_base'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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