<p>如果您使用<a href="https://pypi.python.org/pypi/ruamel.yaml/" rel="nofollow noreferrer">^{<cd1>}</a>¹,通过在StackOverlow上组合<a href="https://stackoverflow.com/a/29604834/1307905">this</a>和<a href="https://stackoverflow.com/a/35406862/1307905">this</a>答案,可以相对容易地实现这一点。在</p>
<p>默认情况下,<code>ruamel.yaml</code>标准化为缩进2,并删除多余的引号。{1{或者不想显式地分析}的输入,并告诉它:</p>
<pre><code>import sys
import ruamel.yaml
import ruamel.yaml.util
yaml_str = """\
nas:
mount_dir: '/nvr'
mount_dirs: ['/mount/data0', '/mount/data1', '/mount/data2']
"""
result, indent, block_seq_indent = ruamel.yaml.util.load_yaml_guess_indent(
yaml_str, preserve_quotes=True)
result['nas']['mount_dirs'][0] = "haha"
ruamel.yaml.round_trip_dump(result, sys.stdout, indent=indent,
block_seq_indent=block_seq_indent)
</code></pre>
<p>代替<code>load_yaml_guess_indent()</code>调用,您可以:</p>
^{pr2}$
<p>如果要在输出中引用<code>haha</code>,请使其成为<code>SingleQuotedScalarString</code>:</p>
<pre><code>result['nas']['mount_dirs'][0] = \
ruamel.yaml.scalarstring.SingleQuotedScalarString("haha")
</code></pre>
<p>这样,输出将是:</p>
<pre><code>nas:
mount_dir: '/nvr'
mount_dirs: ['haha', '/mount/data1', '/mount/data2']
</code></pre>
<p>(假定您的简短示例输入没有块样式序列,则<code>block_sequence_indent</code>无法确定,并且将为None)</p>
<hr/>
<p>使用较新的API时,您可以分别控制映射和序列的缩进:</p>
<pre><code>yaml = ruamel.yaml.YAML()
yaml.indent(mapping=4, sequence=6, offset=3) # not that that looks nice
data = yaml.load(some_stream)
yaml.dump(data, some_stream)
</code></pre>
<p>这将使您的YAML格式保持一致,如果不是这样开始的话,并且在第一次往返之后没有进一步的更改。在</p>
<hr/>
<p>¹<sub>免责声明:我是该软件包的作者。</sub></p>