how to keep null value in yaml file while dumping though ruamel.yaml(通过 ruamel.yaml 转储时如何在 yaml 文件中保留空值)
问题描述
我有 YAML 文件 site.yaml
:
I have YAML file site.yaml
:
Kvm_BLOCK:
ip_address: 10.X.X.X
property: null
server_type: zone
加载然后转储:
ruamel.yaml.dump(site_yaml, new_file, Dumper=ruamel.yaml.RoundTripDumper)
变成了
Kvm_BLOCK:
ip_address: 10.X.X.X
property:
server_type: zone
如何在属性块中保留这个 null
值
how to retain this null
value in property block
推荐答案
YAML 1.2中的null
值(构造为Python的None
)可以表示为null
、Null
、NULL
和 ~
,指定为 这里.
The null
value in YAML 1.2 (constructed as Python's None
) can be represented as null
, Null
, NULL
and ~
, as specified here.
另外:
内容为空的节点被解释为它们是具有空值的普通标量.此类节点通常被解析为空"值.
Nodes with empty content are interpreted as if they were plain scalars with an empty value. Such nodes are commonly resolved to a "null" value.
因此,您的 null
值并没有消失,它只是在使用 ruamel.yaml
时由 null
的默认表示不同地表示代码>RoundTripDump代码>.如果再次加载该输出,您将再次获得 None
作为键 property
Therefore your null
value is not gone, it is just represented differently by the default representation for null
in ruamel.yaml
when using RoundTripDump
. If you load that output again, you once more get a None
as value for the key property
如果您不喜欢这样,您可以通过以下方式更改 all None
/null
值的输出:
If that is not to your liking you can change the output for all None
/null
values by doing:
import sys
import ruamel.yaml
yaml_str = """
Kvm_BLOCK:
ip_address: 10.X.X.X
property: null
server_type: zone
"""
def my_represent_none(self, data):
return self.represent_scalar(u'tag:yaml.org,2002:null', u'NULL')
yaml = ruamel.yaml.YAML()
yaml.representer.add_representer(type(None), my_represent_none)
data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)
将转储:
Kvm_BLOCK:
ip_address: 10.X.X.X
property: NULL
server_type: zone
您可以通过在 Python 中创建不同的类(NULL
、Null
、null
等)并使用不同的表示器来获得更细粒度的控制对于它们中的每一个(与 ruamel.yaml.scalarstring.py
中的 string
子类用于以不同方式表示字符串的方式非常相似(双引号,单引用,文字块样式标量).问题是你不能继承 NoneType
所以这不像字符串标量那样容易透明地完成.
You can get finer grained control by creating different classes in Python (NULL
, Null
, null
, etc. ) and have different representers for each of them (much in the same way that the string
subclasses in ruamel.yaml.scalarstring.py
are used to represent a string in different ways (double quoted, single quoted, literal block style scalar). The problem is that you cannot subclass NoneType
so this is not so easily done transparently as with the string scalars.
这篇关于通过 ruamel.yaml 转储时如何在 yaml 文件中保留空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过 ruamel.yaml 转储时如何在 yaml 文件中保留空值
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01