python - 将 yaml 文件保存到生成器对象到字典 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 传递给 load 函数。
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__()
我会推荐第一个选项供您使用。
推荐阅读
- php - Laravel Symfony/console,由于“无效参数”而导致安装失败?
- c# - 在 C# 中使用随机单词数组
- python - Min Max 类似函数,使用 if best == None 和 Python 中循环内的条件
- aws-amplify - 如何在两个或多个放大控制台应用程序之间共享单个 route53 域
- python-3.x - 在 Django FileField 中,如何设置包含随机 url 的 file.name?
- spring-boot - 尝试在方法逻辑发生之前向前端发送 Http 响应
- javascript - Knex 要求安装 sqlite3 但我使用的是 mysql 数据库
- scala - 从命令行参数化 SBT DockerPlugin
- vba - 使用 VBA 在 Word 中编辑特定的页脚列
- azure-maps - Azure 地图 - 从地图中删除国家边界