Python教程

python中yaml文件之间、文件内部相互引用

本文主要是介绍python中yaml文件之间、文件内部相互引用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.目录结构

|--------a
            |----a.yaml
            |----b.yaml
|--------c
            |----c.yaml
|--------yaml_include.py

2.代码实现yaml_include.py

import yaml
import os.path


class Loader(yaml.Loader):
    def __init__(self, stream):
        self._root = os.path.split(stream.name)[0]
        super(Loader, self).__init__(stream)

    def include(self, node):
        filename = os.path.join(self._root, self.construct_scalar(node))
        with open(filename, 'r') as fr:
            return yaml.load(fr, Loader)

Loader.add_constructor('!include', Loader.include)

def load_yaml(file_name):
    """Load YAML file to be dict"""
    if os.path.exists(file_name):
        with open(file_name, 'r', encoding="utf-8") as fr:
            dict_obj = yaml.load(fr, Loader=Loader)
        return dict_obj
    else:
        raise FileNotFoundError('NOT Found YAML file %s' % file_name)

if __name__ == '__main__':
    yaml_dict = load_yaml("a/a.yaml")
    print(yaml_dict)

3.yaml文件之间相互引用

a.yaml

name: demo
hobby: !include ./b.yaml # 引用当前目录下yaml文件
skill: !include ../c/c.yaml # 引用非当前目录下的yaml文件

b.yaml

- basketball
- Table-Tennis
- swim

c.yaml

- python
- java
- shell
- linux

打印结果:

{
    "hobby": ["basketball", "Table-Tennis", "swim"],
    "name": "demo",
    "skill": ["python", "java", "shell", "linux"]
}

4.yaml文件内部引用

a.yaml

name: demo
maodiao1: &maodian1 # &符号标记锚点1
  a: 1
  b: 2
maodiao2: &maodian2 # &符号标记锚点2
  aa: 11
  bb: 22
haha:
  <<: *maodian1 # 方式一:使用 <<: * 符号引用
heihei: *maodian2 # 方式二:直接使用*号引用

打印结果:

{
    "name": "demo",
    "maodiao1": {"a": 1, "b": 2},
    "maodiao2": {"aa": 11, "bb": 22},
    "haha": {"a": 1,"b": 2},
    "heihei": {"aa": 11,"bb": 22}
}

5. 文件之间与文件内部混合引用

a.yaml

name: demo
maodian1: &maodian1 # &符号标记锚点1
  hobby: !include ./b.yaml # 引用当前目录下yaml文件
  skill: !include ../c/c.yaml # 引用非当前目录下的yaml文件
maodiao2: &maodian2 # &符号标记锚点2
  aa: 11
  bb: 22
haha:
  <<: *maodian1 # 方式一:使用 <<: * 符号引用
heihei: *maodian2 # 方式二:直接使用*号引用

b.yaml

- basketball
- Table-Tennis
- swim

c.yaml

- python
- java
- shell
- linux

打印结果

{
	"name": "demo",
	"maodian1": {
        "hobby": ["basketball", "Table-Tennis", "swim"],
        "skill": ["python", "java", "shell", "linux"]
    },
    "maodiao2": {"aa": 11,"bb": 22},
    "haha": {
        "hobby": ["basketball", "Table-Tennis", "swim"],
        "skill": ["python", "java", "shell", "linux"]
    },
    "heihei": {"aa": 11,"bb": 22}
}
这篇关于python中yaml文件之间、文件内部相互引用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!