python使用Pyyaml和keep form

2024-06-16 19:10:40 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个配置文件,我用PyYAML来改变它的一些值,然后我写一些配置文件,但是它会改变我的格式,这让我很困惑。在

 $ results.yaml 
 nas:
     mount_dir: '/nvr'
     mount_dirs: ['/mount/data0', '/mount/data1', '/mount/data2']

# yaml.py

import yaml.py

conf = open("results.conf", "r")
results = yaml.load(conf)
conf.close()

result['nas']['mount_dirs'][0]= "haha"

with open('/home/zonion/speedio/speedio.conf', 'w') as conf:
    yaml.dump(speedio, conf, default_flow_style=False)

conf.close()

但它改变了我的格式,我该怎么办?在

^{pr2}$

Tags: pyyamlcloseconf格式配置文件diropen
3条回答

ruamel实现了一个往返加载程序和转储程序,请尝试:

import ruamel.yaml
conf = open("results.conf", "r")
results = ruamel.yaml.load(conf, ruamel.yaml.RoundTripLoader)
conf.close()
results['nas']['mount_dirs'][0] = "haha"
with open('/home/zonion/speedio/speedio.conf', 'w') as conf:
  ruamel.yaml.dump(results, conf, ruamel.yaml.RoundTripDumper)

如果您使用^{}¹,通过在StackOverlow上组合thisthis答案,可以相对容易地实现这一点。在

默认情况下,ruamel.yaml标准化为缩进2,并删除多余的引号。{1{或者不想显式地分析}的输入,并告诉它:

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)

代替load_yaml_guess_indent()调用,您可以:

^{pr2}$

如果要在输出中引用haha,请使其成为SingleQuotedScalarString

result['nas']['mount_dirs'][0] = \
       ruamel.yaml.scalarstring.SingleQuotedScalarString("haha")

这样,输出将是:

nas:
    mount_dir: '/nvr'
    mount_dirs: ['haha', '/mount/data1', '/mount/data2']

(假定您的简短示例输入没有块样式序列,则block_sequence_indent无法确定,并且将为None)


使用较新的API时,您可以分别控制映射和序列的缩进:

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)

这将使您的YAML格式保持一致,如果不是这样开始的话,并且在第一次往返之后没有进一步的更改。在


¹免责声明:我是该软件包的作者。

ruamel.yaml不幸的是,没有完全保留原始格式,引用其docs

Although individual indentation of lines is not preserved, you can specify separate indentation levels for mappings and sequences (counting for sequences does not include the dash for a sequence element) and specific offset of block sequence dashes within that indentation.

我不知道有哪个Python库能做到这一点。在

当我需要在不触及YAML文件格式的情况下更改YAML文件时,我不情愿地使用regexp(因为它几乎和parsing XHTML with it一样糟糕)。在

请随时提出更好的解决方案,如果你知道的话,我很乐意了解它!在

相关问题 更多 >