如何将YAML文件中的特定数据包含在另一个文件中?

时间:2020-09-15 09:23:00

标签: python yaml

我与此question的结构和场景非常相似,这对我有很大帮助,但是我正在寻找一个更具体的情况,我想仅将来自另一个yaml文件的数据添加到我的yaml文件中,而不是完整的文件。像这样:

更新:抱歉,我更正了以下文件的结构以正确描述我的情况。

foo.yaml

a: 1
b:
    - 1.43
    - 543.55
    - item : !include {I wanna just the [1, 2, 3] from} bar.yaml

bar.yaml

- 3.6
- [1, 2, 3]

现在,我将导入所有第二个文件,但是自昨天以来,我并不需要所有文件,也没有找到合适的解决方案。下面是我的实际结构:

foo.yaml

variables: !include bar.yaml #I'm importing the entire file for now and have to navegate in that to get what I need.
a: 1
b:
    - 1.43
    - 543.55

1 个答案:

答案 0 :(得分:1)

您可以编写自己的自定义包含构造函数:


bar_yaml = """
- 3.6
- [1, 2, 3]
"""

foo_yaml = """
variables: !include [bar.yaml, 1]
a: 1
b:
    - 1.43
    - 543.55
"""

def include_constructor(loader, node):
  selector = loader.construct_sequence(node)
  name = selector.pop(0)
  # in actual code, load the file named by name.
  # for this example, we'll ignore the name and load the predefined string
  content = yaml.safe_load(bar_yaml)
  # walk over the selector items and descend into the loaded structure each time.
  for item in selector:
    content = content[item]
  return content

yaml.add_constructor('!include', include_constructor, Loader=yaml.SafeLoader)

print(yaml.safe_load(foo_yaml))

!include会将给定序列中的第一项视为文件名,并将随后的项视为序列索引(或字典键)。例如。您可以执行!include [bar.yaml, 1, 2]只加载3