• 01 python基础——python解析yaml类型文件


    目录

    一、yaml介绍

            yaml全称Yet Another Markup Language(另一种标记语言)。采用yaml作为配置文件,文件看起来直观、简洁、方便理解。yaml文件可以解析字典列表和一些基本变量的数据结构。

    1.1 yaml语法规则

    1. 大小写敏感
    2. 使用缩进表示层级关系
    3. 缩进时不允许使用tab键,只可以使用空格
    4. 缩进时空格数目不重要,只要相同元素左侧对其即可
    5. # 表示当行注释

    1.2 yaml环境搭建

    -- 安装pip之后,执行以下操作
    pip install pyyaml
    

    二、yaml文件格式

    2.1 字典

    # 普通字典
    key1:value
    
    # 嵌套字典
    key2:
        sub_key1:value1
        sub_keys:value2
    

    2.2 列表

    # 下面同级的para1、para2以及para3在同一列表中
    - para1
    - para2
    - para3
    

    2.3 普通变量

            yaml配置文件,可以解析数字字符串布尔类型数据、时间日期格式,也可以对数字、布尔类型数据做强制转换,使其在解析成为字符串类型的数据

    2.3.1 yaml之None的表示方法

    # 在yaml中~表示None
    ~
    

    2.3.2 yaml强制转换数据类型

    # 在yaml配置中,!!str data表示把数据data强制转换为str类型
    age: !!str 18
    

    2.3.3 yaml日期格式表示

    # 时间和日期格式均为iso8601
    
    # 日期表示
    data_today:2018-04-22
    
    # 时间格式
    # 下面代表北京时间2018,04,22的16:55:30,因为北京位于东八区,所以后面加了08:00,时间的秒可以写到小数点后两位
    time_now:2018-04-22T16:55:30+08:00
    

    三、yaml文件读取

    导入yaml模块,需使用官方的导入方法,可以兼容windows和linux平台

    import yaml
    try:
        from yaml import CLoader as Loader, CDumper as Dumper
    except ImportError:
        from yaml import Loader, Dumper
    yaml_file= open("path", "r")
    data = yaml.load(yaml_file)
    

    四、 使用案例

    4.1 待操作yaml文件

    # 文件名test.yaml
    bind1:
      hostname: ubuntu test
      remote_users:
        - user1:
          username: root
          auth_type: ssh-key
          password: 123
        - user2:
          username: gungun
          auth_type: ssh-password
          password: gungun123
      groups:
        - bj_group
      user_profiles:
        - gungun
        - xiangqiangun
    

    4.2 yaml文件读取示例

    import yaml
    try:
        from yaml import CLoader as Loader, CDumper as Dumper
    except ImportError:
        from yaml import Loader, Dumper
    
    yaml_file = open("test.yaml",'r')
    data = yaml.load(yaml_file)
    print("data_type:", type(data))
    print("data_content:
    ", data)
    

    打印结果:

    data_content:
     {'bind1': {'user_profiles': ['gungun', 'xiangqiangun'], 'hostname': 'ubuntu test', 'groups': ['bj_group'], 'remote_users': [{'username': 'root', 'auth_type': 'ssh-key', 'user1': None, 'password': 123}, {'username': 'gungun', 'auth_type': 'ssh-password', 'user2': None, 'password': 'gungun123'}]}}
    
  • 相关阅读:
    MyBatis 中#{}和${}区别
    MyBatis缓存机制
    SpringBoot整合RabbitMQ
    Jackson2JsonRedisSerializer和GenericJackson2JsonRedisSerializer的区别
    Docker安装MySql
    Python3网络爬虫(七):使用Beautiful Soup爬取小说
    python3 爬虫内涵段子
    python3 爬虫百度贴吧
    Python3网络爬虫(五):Python3安装Scrapy
    Requests: 模块
  • 原文地址:https://www.cnblogs.com/gupan/p/8908351.html
Copyright © 2020-2023  润新知