Read yaml configuration file data based on Python and pyyaml


1、 First, we need to install pyyaml third-party library

Just use PIP install pyyaml directly (I installed pyyaml before, so I am prompted that pyyaml is in this directory, version 5.1.2)

2、 Let’s first look at the format of the data in my yaml configuration file


1. Case sensitive

2. Use indent to represent hierarchy

3. The space is used when indenting, not the tab key (because when writing Python scripts, you may be used to indent with the tab key, the indentation here can only use the space. As long as the same level is aligned, it doesn’t matter if one or two spaces are empty.)

4. The # sign indicates a comment

This is the basic syntax of Python code


3、 How to read yaml file

Note: Here we import pyyaml instead of pyyaml.

4、 Take a look at the output:

res1= {'mysql': {'host': 'value_host', 'port': 'value_port', 'user': 'value_user', 'password': 'value_password', 'database': 'value_databass', 'use_unicode': 'value_use_unicode', 'charset': 'value_charset'}, 'url': {'url': 'value_url'}, 'data': {'phone': 'value_phone', 'pwd': 'value_pwd', 'memberId': 'value_memberId'}}
res1= value_url

You can see that the data in the yaml configuration file after reading is read in the dictionary type. You can compare the data storage format in the previous yaml file to see why the indentation of the yaml file should be strictly controlled.

Recommended Today

Summary of recent use of gin

Recently, a new project is developed by using gin. Some problems are encountered in the process. To sum up, as a note, I hope it can help you. Cross domain problems Middleware: func Cors() gin.HandlerFunc { return func(c *gin.Context) { //Here you can use * or the domain name you specify c.Header(“Access-Control-Allow-Origin”, “*”) //Allow header […]