Briefly introduce the third party library yaml of Python
- 2021-11-13 02:07:31
- OfStack
1. Basic introduction to yaml
yaml is the third library of Python. YAML is a human friendly data serialization standard for all programming languages (YAML is a data serialization standard friendly to all programming languages).
However, in order to emphasize that the language is data-centric, rather than markup language, it is renamed with a back-to-back word. It is an intuitive data serialization format that can be recognized by computers. It is a programming language with high readability, easy to be read by human beings, easy to interact with scripting languages (not only Python), and used to express data sequences. The essence of YAML language is a general data serialization format.
2. Applicable scenarios
Used in footstep language, it is simple to realize and low in parsing cost; Serialization; Writing configuration files when programming is faster than xml and more powerful than ini documents. YAML is a language dedicated to writing configuration files, which is very concise and powerful, and is far more convenient than JSON format.
3. Basic grammar rules
Case sensitive; Use indentation to represent hierarchical relationships; The Tab key is not allowed for indentation, only spaces are allowed; The number of spaces indented is not important, as long as the left side of elements of the same level is aligned (1 is 2 or 4 spaces); # Indicates the comment on the current line.
4. Three data structures supported by YAML
Object: The collection of key-value pairs, also known as mapping (mapping)/hashing (hashes)/dictionary (dictionary); Array: A set of values arranged in order, also known as sequence (sequence)/list (list); Scalar: A single, non-divisible value.
4.1 Objects
It is represented by a colon and has the format key: value. A space must be added after the colon.
Use indentation to represent hierarchical relationships, as follows:
key:
child_key1: value1
child-key2: value2
YAML also supports streaming (flow) syntax to represent objects. The above example can be written as:
key: {child_key1: value1, child_key2: value2}
This is a dictionary nested dictionary in Python, which reads as follows:
"key": {
"child_key1":"value1",
"child_key2":"value2"
}
For more complex object formats, you can use a question mark plus a space to represent a complex key, and a colon plus a space to represent an value:
?
- complex_key1
- complex_key2
:
- complex_value1
- complex_value2
The above representation: The attribute of the object is an array [complex_key1, complex_key2], and its corresponding value is also an array [complex_value1, complex_value2].
4.2 Array
Use a dash and a space to represent an array item:
hobby:
- python
- test
It can also be said:
-
- python
- test
It can be simply understood as: [[python, test]]
Let's look at a relatively complicated example:
role:
-
id: 1
name: developer
auth: dev
-
id: 2
name: tester
auth: test
It can be understood that the role attribute is an array, and each array element is composed of three attributes: id, name and auth.
It is expressed as follows in the form of flow (flow):
role: [{id: 1, name: developer, auth: dev}, {id: 2, name: tester, auth: test}]
4.2. 1 Objects and arrays
It can be used in combination to form a composite structure
languages:
- Ruby
- Perl
- Python
websites:
YAML: yaml.org
Ruby: ruby-lang.org
Python: python.org
Perl: use.perl.org
4.3 Scalar
Scalar is the most basic and indivisible value. YAML provides a variety of constant structures: integer, floating point, string, NULL, date, Boolean, time.
int:
- 123
- 0b1010_0111_0100_1010_1110 # 2 Binary representation
float:
- 3.14159
- 6.6e+5 # Scientific notation can be used
string:
- 'Hello world!' # Special characters can be wrapped in double quotation marks or single quotation marks, and double quotation marks do not escape special characters.
- newline
newline2 # String can be split into multiple lines, and each 1 Guild will be transformed into 1 Spaces
null:
nodeName: 'node'
parent: ~ # Use ~ Denote null
boolean:
- TRUE # true Or True All right
- FALSE # false Or False All right
date:
- 2018-12-29 # Date must be used ISO 8601 Format, namely yyyy-MM-dd
datetime:
- 2018-12-29T18:43:21+08:00 # Time use ISO 8601 Format, time and date used between T Connect, and finally use the + Represents time zone
4.4 There are also one special symbol
4.4. 1--YAML can be used in the same file to denote the beginning of a document
key: {child_key1: value1, child_key2: value2}
0
The above example defines two profile, one development, and one production.
You can also use-to split different contents, such as logging:
key: {child_key1: value1, child_key2: value2}
1
4.4. 2... and-are used together to represent the end of 1 in 1 configuration file
key: {child_key1: value1, child_key2: value2}
2
This example is equivalent to writing two yaml configuration items in a single yaml file.
4.4. 3 Used in YAML! ! Do type casting
string:
- !!str 123456
- !!str true
It is equivalent to forcing numbers and Boolean types into strings (there are many types allowed to be converted).
4.4.4 > Represents a collapsed line break in a string; Leave the line break. These two symbols are commonly used for strings in YAML
key: {child_key1: value1, child_key2: value2}
4
The result of accomplistment is:
key: {child_key1: value1, child_key2: value2}
5
The result of status is:
key: {child_key1: value1, child_key2: value2}
6
4.4. 5 Citation. Repeated content can be used in YAML & To complete the anchor point definition, and to complete the anchor point reference with *
key: {child_key1: value1, child_key2: value2}
7
In hr, the & SS sets an anchor point (reference) for Sammy Sosa, named SS;; In rbi, the anchor point usage is completed with * SS. The result is:
{rbi=[Mark McGwire, Ken Griffey], hr=[Mark McGwire, Sammy Sosa]}
It can also be defined as follows:
key: {child_key1: value1, child_key2: value2}
9
You can also define more complex content with anchors:
default: &default
- Mark McGwire
- Sammy Sosa
hr: *default
hr is equivalent to referencing an default array. However, hr: * default must be written on the same line.
4.4. 6 Consolidation of contents. It is mainly used in conjunction with anchor points, and can directly merge the contents of one anchor point into one object
merge:
- &CENTER { x: 1, y: 2 }
- &LEFT { x: 0, y: 2 }
- &BIG { r: 10 }
- &SMALL { r: 1 }
sample1:
<<: *CENTER
r: 10
sample2:
<< : [ *CENTER, *BIG ]
other: haha
sample3:
<< : [ *CENTER, *BIG ]
r: 100
In merge, four anchor points are defined, which are used in sample respectively.
In sample1, < < : * CENTER means quoting {x: 1, y: 2} and merging into sample1, then the merging result is: sample1= {r=10, y=2, x=1}
In sample2, < < : [* CENTER, * BIG] means to jointly reference {x: 1, y: 2} and {r: 10} and merge into sample2, then the result of the merge is: sample2= {other=haha, x=1, y=2, r=10}
In sample3, * CENTER and * BIG are introduced, and r: 100 is used to override the introduced r: 10, so the value of sample3 is: sample3= {r=100, y=2, x=1}
With merging, we can extract the same basic configuration from the configuration and merge references in different sub-configurations.
5. Actual combat
5.1 Installing yaml
The yaml package name is pyyaml, but the import is yaml.
5.2 Python Use yaml
Take "reading yaml file with Python (suffix can be. yml or. yaml)" as an example: first read file data with open method, and then convert it into dictionary with load method (load method is similar to load of json).
In the same folder, write an yaml file called cfg. yml as follows:
nb:
user: admin
psw: 123456
Write the. py file that reads the yaml file, named readyml. py, as follows:
"key": {
"child_key1":"value1",
"child_key2":"value2"
}
3
Among them, the two most important methods:
load (), parsing yaml document and returning 1 Python object; load_all (), if it is string or the file contains several yaml documents, this method can be used to parse all documents and generate an iterator; dump (), which generates an Python object into an yaml document; dump_all (), which outputs multiple segments into a single yaml document.