该ruamel.yaml包是专门(由我从PyYAML开始)做这种往返,编程,更新的增强。
如果您从开始(请注意,我删除了多余的初始空格):
init_config: {}instances: - host: <IP> # update with IP username: <username> # update with user name password: <password> # update with password并运行:
import ruamel.yamlfile_name = 'input.yaml'config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))instances = config['instances']instances[0]['host'] = '1.2.3.4'instances[0]['username'] = 'Username'instances[0]['password'] = 'Password'with open('output.yaml', 'w') as fp: yaml.dump(config, fp)输出将是:
init_config: {}instances: - host: 1.2.3.4# update with IP username: Username # update with user name password: Password # update with password映射键(的顺序
host,
username和
password),风格和 评论 将被保留,没有任何进一步的具体行动。
您可以手动进行传统的加载,然后自己设置缩进值,而不用猜测缩进和块序列的缩进:
yaml = ruamel.yaml.YAML()yaml.indent(mapping=6, sequence=4)with open(file_name) as fp: config = yaml.load(fp)
如果您查看此答案的历史记录,则可以看到如何使用更受限的,类似于PyYAML的API来执行此操作。



