python修改yaml文件_如何使用python更新yaml文件

ruamel.yaml包是专门增强的(由我从PyYAML开始))来进行这种往返,程序化,更新.

如果你开始(请注意我删除了额外的初始空格):

init_config: {}

instances:

- host: # update with IP

username: # update with user name

password: # update with password

并运行:

import ruamel.yaml

file_name = 'input.yml'

from ruamel.yaml.util import load_yaml_guess_indent

config, ind, bsi = 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'

ruamel.yaml.round_trip_dump(config, open('output.yml', 'w'),

indent=ind, block_seq_indent=bsi)

输出将是:

init_config: {}

instances:

- host: 1.2.3.4 # update with IP

userna

你可能感兴趣的:(python修改yaml文件)