簡體   English   中英

將yaml文件保存到生成器對象到字典python

[英]Save a yaml file to a generator object to a dictionary python

我在將 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

只有在沒有加載程序的情況下調用被棄用。 您始終可以將 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__()

我會推薦第一個選項供您使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM