[英]Loading empty dictionary when YAML file is empty (Python 3.4)
我有一个空的YAML文件,当我加载它时,我想将其作为空字典加载。 例如,我有
import yaml
with open('an_empty_file.yml', 'r') as config_file:
config=yaml.load(config_file)
print(config)
None
事实证明, yaml.load(config_file)
将返回一个NoneType
对象,我认为这是有道理的。 有一种简单的方法可以返回一个空字典吗?
如果它返回None
,你可以使用or
如果yaml.load
返回None,你的配置默认会保存一个空字典:
config = yaml.load(config_file) or {}
最终,这里发生的事情从左侧开始:
我们现在正在为config分配一个值。 我们声明将yaml.load(config_file)
分配给config,但是,通过使用or
,我们在这个语句中说的是,如果它( yaml.load
)计算为None或False条件(即在此对我们来说,没有),然后我们将{}
分配给配置。
快速演示将空字符串作为config_file:
>>> import yaml
>>> config_file = ''
>>> config = yaml.load(config_file) or {}
>>> print(config)
{}
在顶层,YAML文件可以有
:
可选地使用{}
流式样式), -
如果是块样式而指示的序列,如果是流样式则为[ ]
您的文件不是映射或序列,因此它是标量,因为具有空表示的标量被认为与指定相同
null
在文件中。
要将其作为空字典加载而不是作为无加载,您可以执行以下操作:
with open('an_empty_file.yml', 'r') as config_file:
config = yaml.load(config_file)
config = {} if config is None else config
print(config)
你永远不应该尝试做一些做法:
config = yaml.load(config_file) or {}
因为这也会导致单个标量为0
文件:
0
单标量浮点数0.0
:
0.0
使用十六进制标量0x0
:
0x0
空双引号标量""
""
空单引号标量''
''
空折叠标量:
>
使用空的文字样式标量:
|
使用单个布尔值False
:
False
或者no
¹:
no
或off
¹:
off
以及空序列:
[
]
导致config
为空字典。
将错误地更改为空字典的不同文件内容的数量是无穷无尽的。
¹这是PyYAML从未更新为1.1到2009年发布的1.2标准的结果。如果是,它也会转换0o0形式的0o0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.