【问题标题】:Save a yaml file to a generator object to a dictionary python将 yaml 文件保存到生成器对象到字典 python
【发布时间】:2019-12-27 15:22:56
【问题描述】:

我在将 YAML 文件保存到 python 字典时遇到了很多问题。我将在下面显示我采取的两条路线,均不是最佳路线。

Yaml 文件:

modules:
    module_1: True
    module_2: True
    module_3: False
scenarios:
    constant:
        start_date: "2018-09-30"
        end_date: "2019-09-30"
    adverse:
        start_date: "2019-09-30"
        end_date: "2022-09-30"

路线 1:将 YAML 文件直接保存到字典中,而不指定现在已弃用的加载器

import yaml
filepath = "C:\\user\\path\\file.yaml"
_dict = yaml.load(open(filepath))
print(type(_dict))
>>> <class 'dict'>

error message: Calling yaml.load() without loader=... is depreciated, as it is unsafe

路线 2:作为生成器加载(不可下标)

import yaml
filepath = "C:\\user\\path\\file.yaml"
document = open(filepath, "r")
dictionary = yaml.safe_load_all(document)

print(type(dictionary)
>>> <generator object>

print(dictionary["modules"]["module_1"]
>>> generator object is not subscriptable

有没有办法可以安全地将我的 yaml 文件导入字典?我希望在我的 python 项目中使用字典而不是创建全局变量等。

例子:

if _dict["modules"]["module_1"]:
    # Do something

【问题讨论】:

  • 尝试使用safe_load 代替safe_load_all
  • Adeom 提供了答案

标签: python dictionary import yaml


【解决方案1】:

仅在没有加载程序的情况下调用已被弃用。您始终可以将 SafeLoader 传递给加载函数。

import yaml

with open(filepath, 'r') as stream:
    dictionary = yaml.load(stream, Loader=yaml.SafeLoader)

这应该会返回您的字典。

编辑:

而对于yaml.safe_load_all,只需要调用generator.__next__()即可获取字典。

import yaml
filepath = "C:\\user\\path\\file.yaml"
document = open(filepath, "r")
generator = yaml.safe_load_all(document)
dictionary = generator.__next__()

我会推荐第一个选项供您使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2021-03-23
    • 1970-01-01
    • 2014-05-17
    • 2013-09-04
    相关资源
    最近更新 更多