<p><a href="https://pypi.python.org/pypi/ruamel.yaml" rel="nofollow noreferrer">ruamel.yaml</a>包被特别增强(由我从PyYAML开始)来执行这种往返、编程、更新。</p>
<p>如果您以(请注意,我删除了额外的初始空格):</p>
<pre><code>init_config: {}
instances:
- host: <IP> # update with IP
username: <username> # update with user name
password: <password> # update with password
</code></pre>
<p>然后运行:</p>
<pre><code>import ruamel.yaml
file_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)
</code></pre>
<p>输出为:</p>
<pre><code>init_config: {}
instances:
- host: 1.2.3.4 # update with IP
username: Username # update with user name
password: Password # update with password
</code></pre>
<p>映射键(<code>host</code>,<code>username</code>和<code>password</code>)的顺序、样式和注释都将被保留,而无需任何进一步的特定操作。</p>
<p>与猜测缩进和块序列缩进不同,您可以手动执行传统加载,并自行设置缩进值:</p>
<pre><code>yaml = ruamel.yaml.YAML()
yaml.indent(mapping=6, sequence=4)
with open(file_name) as fp:
config = yaml.load(fp)
</code></pre>
<hr/>
<p>如果您查看这个答案的历史,您可以看到如何使用一个更有限的、类似PyYAML的API来实现这一点。</p>