python note 14 - read yaml configuration file

Introduction to yaml

1.yaml [ˈjæməl]: Yet Another Markup Language: Another markup language. yaml is a language specially used to write configuration files. It is very simple and powerful. I used to use ini to write configuration files. After reading yaml, I found that this is more intuitive and convenient, a bit similar to the json format.

2.yaml basic grammar rules:

  • Case Sensitive
  • Use indentation to indicate hierarchy
  • Tab key is not allowed when indenting, only spaces are allowed.
  • The number of spaces indented does not matter, as long as elements at the same level are left aligned
  • # indicates a comment, from this character to the end of the line, it will be ignored by the parser, this is the same as python's comment

3. There are three data structures supported by yaml:

  • Object: A collection of key-value pairs, also known as mapping/hashes/dictionary
  • Array: A set of values ​​in order, also known as a sequence/list
  • scalars: single, indivisible values. String, Boolean, Integer, Float, Null, Time, Date

install yaml

1. Install the pyyaml ​​module using pip

pip install pyyaml

key-value pair (dict)

1. The key-value pair in yaml, that is, the dictionary (dict) data type in python, such as the dictionary in python, how to write it in yaml

# python3.6
{
"user": "admin",
"psw": "123456, }

In the yaml file you can write:

# yaml
user: admin
psw: 123456

2. Dictionary nested dictionary

# python3.6
"nb1": {
        "user": "admin",
        "psw": "123456, }

3. The yaml file can be written like this:

# yaml
nb1:
    user: admin
    psw: 123456

4. The example of reading yaml files with python is as follows. First, use the open method to read the file data, and then use the load method to convert it into a dictionary. This load is similar to the load in json.

# coding:utf-8
import yaml
import os

#Get the folder path where the current script is located 
curPath = os.path.dirname(os.path.realpath( __file__ ))
 #Get the yaml file path 
yamlPath = os.path.join(curPath, " cfgyaml.yaml " )

# The open method opens and reads it directly 
f = open(yamlPath, ' r ' , encoding= ' utf-8 ' )
cfg = f.read()
 print (type(cfg))   #The read is a string 
print (cfg)

d = yaml.load(cfg) #Use   the load method to convert the dictionary 
print (d)
 print (type(d))

 

The running result is as follows

sequence (list)

1. Write an array in yaml, preceded by a '-' symbol , as follows

- admin1: 123456
- admin2: 111111
- admin3: 222222

Corresponding to the list in python

[{'admin1': 123456},
{'admin2': 111111}, 
{'admin3': 222222}]

Note: Numbers are read as int or float type

scalar (str)

1. Numbers of type int and float

n1: 12.30 

Corresponds to python

{'n1': 12.3}

2. Boolean values ​​are represented by true and false

n2: true 
n3: false 

Corresponds to python

{'n2': True, 'n3': True}

3.None is represented by ~

n4: ~

Corresponds to python

{'n4': None}

4. The time is in ISO8601 format.

time1: 2001-12-14t21:59:43.10-05:00 

Corresponds to python

{'time1': datetime.datetime(2001, 12, 15, 2, 59, 43, 100000)}

5. The date is represented by year, month and day in compound iso8601 format.

date1: 2017-07-31

Corresponds to python

{'date1': datetime.date(2017, 7, 31)}

6. Use two exclamation marks to cast the data type.

# int转str
n6: !!str 123  

Corresponds to python

{'n6': '123'}
# bool值转str
n7: !!str true

Corresponds to python

{'n7': 'true'}

7. Write the following in the yaml file:

n1: 12.30
n2: true
n3: false n4: ~ time1: 2018-04-18t21:59:43.10+08:00 date1: 2018-04-18 n6: !!str 123 n7: !!str true

python reads the result:

{'n1': 12.3, 
'n2': True, 
'n3': False, 'n4': None, 'time1': datetime.datetime(2018, 4, 18, 13, 59, 43, 100000), 'date1': datetime.date(2018, 4, 18), 'n6': '123', 'n7': 'true'}

Mixed use

1.List nested dict, write the following in yaml:

- user: admin1
  psw: '123456'

- user: admin2
 psw: '111111' - user: admin3  psw: '222222'

The result read with python:

[{'user': 'admin1', 'psw': '123456'},
{'user': 'admin2', 'psw': '111111'}, {'user': 'admin3', 'psw': '222222'}] 

2. dict nested list, write the following in yaml:

nub1:
    - admin1
    - '123456'

nb2:
    - admin2
    - '111111'
 nb3: - admin3 - '222222'

The result read with python:

{'nub1': ['admin1', '123456'],
'nb2': ['admin2', '111111'], 'nb3': ['admin3', '222222']}

Guess you like

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