01 python basics - python parsing yaml type files

content

[TOC]

1. Introduction to yaml

        The full name of yaml is Yet Another Markup Language. Using yaml as the configuration file, the file looks intuitive, concise, and easy to understand. yaml files can parse dictionaries , lists and some basic variable data structures.

1.1 yaml grammar rules

  1. Case Sensitive
  2. Use indentation to indicate hierarchy
  3. Tab key is not allowed when indenting, only spaces are allowed
  4. The number of spaces does not matter when indenting, as long as the same element is aligned to the left
  5. # Indicates the current line comment

    1.2 yaml environment construction

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

2. yaml file format

2.1 Dictionaries

# 普通字典
key1:value

# 嵌套字典
key2:
    sub_key1:value1
    sub_keys:value2

2.2 List

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

2.3 Ordinary variables

        The yaml configuration file can parse numbers , strings , Boolean type data, time and date formats , and can also perform forced conversion on numbers and Boolean type data to make it parsed into string type data.

2.3.1 Representation of None in yaml

# 在yaml中~表示None
~

2.3.2 yaml cast data type

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

2.3.3 yaml date format representation

# 时间和日期格式均为iso8601

# 日期表示
data_today:2018-04-22

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

Three, yaml file reading

To import the yaml module, you need to use the official import method, which is compatible with windows and linux platforms

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)

3. Use Cases

3.1 yaml file to be operated

# 文件名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

3.2 yaml file reading example

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:\n", data)

print result:

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'}]}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324726232&siteId=291194637