python常用库 - 用PyYAML库读取yml配置文件

   YAML语言是以数据为核心,而不以置标语言为重点,她简洁轻便可读性高,专门用来写配置,远比JSON格式方便,极易上手,墙裂推荐~

 

一. 如果你想运行下方的python代码示例,请先检查2点:

1. 已安装PyYAML

pip install PyYAML

2. python3.6.8环境自测成功,理论上python3.x.x都可运行

 

二.在python脚本里可以用以下2个方法读取yaml配置:

1. 将yaml格式的字符串直接写在python脚本中:

# -*- coding: utf-8 -*-
__author__ = 'TerryJay'

import yaml

    yml_str = """
    root:
      user:
        name: superman
        sex: man
      company:
        floor: 10
        number: 9527
    """

    # load方法转出为字典类型
    yml_data = yaml.load(yml_str)
    print(yml_data)

2. 将配置单独写在"test_config.yml"文件中,再用python读取她的数据:

文件目录结构:

project/
|   |-- __init__.py
|   |-- test.py
|   |-- test_config.yml

数据和代码:

# 文件名test_config.yml
root:
  user:
    name: superman
    sex: man
  company:
    floor: 10
    number: 9527
# 文件名test.py

# -*- coding: utf-8 -*-
__author__ = 'TerryJay'

import yaml


class yaml_Analysis:
    def __init__(self):
        self.data = None

    def get_config(self):
        with open('./test_config.yml', 'r', encoding="utf-8") as f:
            yml_data = f.read()

            # load方法转出为字典类型
            self.data = yaml.load(yml_data)
        return self.data

# 打印测试
if __name__ == '__main__':

    y = yaml_Analysis()
    print(y.get_config())
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章