程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Explain Pythons pyyaml module in detail

編輯:Python

One : What is? yaml

        yaml Its English name is Yet Another Markup Language, The literal translation is markup language .yaml It is often used to write configuration files , such as yaml Configuration file in Kubernetes It is widely used , learn Kubernetes Must learn first yaml File format .

        Let's start with a brief introduction yanm Basic syntax :

  • Case sensitive
  • Use indentation to indicate hierarchy
  • Indentation is not allowed Tab key , Only Spaces are allowed .
  • The number of Spaces indented is not important , As long as the elements of the same level are aligned to the left
  • # Notation , From this character to the end of the line , Will be ignored by the parser , This and python The comments are the same

  Two : install pyyaml

        pyyaml yes python Third party library , You need to install it manually to use

pip install pyyaml

          This installation is pyyaml Of 6.0 edition

  3、 ... and :pyyaml Use

 1, Read yaml file

        First look at what has been prepared yaml file

 First level title :
Secondary title 1:
b:1
c:2
a:3
Secondary title 2:
f:7
t:8
z:9

  use yaml Of load Method to load a yaml File stream , Back to a json object

import yaml
with open('./file.yaml', 'r', encoding='utf-8') as f:
data = yaml.load(stream=f, Loader=yaml.FullLoader)
print(data)

  The operation results are as follows :

  For beginners python In fact, the first-hand information of the students is better to check the description of their own methods and attributes in the module , How to check help Well , On the surface of the above load Methods as an example ,help('yaml.load') The method documentation will be displayed

[email protected]:~# python3
Python 3.4.3 (default, Nov 12 2018, 22:25:49)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import yaml
>>>
>>> help('yaml.load')

  The description documents are as follows :

 2, write in yaml file

with open('./data_yaml.yaml', 'w', encoding='utf-8') as f:
yaml.dump(data=data, stream=f, allow_unicode=True, sort_keys=False, indent=4)

The files it writes are as follows :

3,dump_all Use

         If you want to put multiple Python The object is serialized to a YAML Streaming , have access to  yaml.dump_all  function . This function accepts a Python List or generator object as the first parameter , Represents multiple... To be serialized Python object

>>> obj = [{'name': 'bob', 'age': 19}, {'name': 20, 'age': 23}, {'name': 'leo', 'age': 25}]
>>> print(yaml.dump_all(obj))
{age: 19, name: bob}
--- {age: 23, name: 20}
--- {age: 25, name: leo}

   yaml.dump  and  yaml.dump_all  Method also supports multiple keyword parameters , Used to specify the generated YAML Streaming YAML The style of the document and whether it contains other information . Let's introduce the meaning and usage of each parameter in detail

stream

Specifies that due to output YAML Stream's open file object . The default value is None, Indicates that... Is returned as the return value of the function .

default_flow_style

Whether to display sequence and mapping in flow style by default . The default value is None, Represents for a that does not contain nested sets YAML Streams use stream styles . Set to True when , Sequences and maps use block styles .

default_style

The default value is None. Indicates that scalars are not wrapped in quotation marks . Set to '"' when , Indicates that all scalars are enclosed in double quotes . Set to "'" when , Indicates that all scalars are wrapped in single quotation marks .

canonical

Whether to display in specification form YAML file . The default value is None, It means to format with the values set by other keyword parameters , Instead of using the canonical form . Set to True when , Will be displayed as a specification YAML What's in the document .

indent

Indicates the indent level . The default value is None, Indicates that the default indentation level is used ( Two spaces ), Can be set to other integers .

width

Represents the maximum width of each row . The default value is None, Indicates that the default width is used 80.

allow_unicode

Whether to allow YAML Appears in the stream unicode character . The default value is False, Would be right unicode Character escape . Set to True when ,YAML The document will normally display unicode character , There will be no escape .

line_break

Set line breaks . The default value is None, Indicates that the newline character is '', Empty space . It can be set to \n、\r or \r\n.

encoding

Use the specified encoding for YAML Stream to encode , Output as byte string . The default value is None, Means no coding , The output is a general string .

explicit_start

Every YAML Whether the document contains an explicit instruction end tag . The default value is None, Indicates that there is only one in the stream YAML The document does not contain an explicit instruction end tag . Set to True when ,YAML All in the stream YAML Documents contain an explicit instruction end tag .

explicit_end

Every YAML Whether the document contains an explicit document end tag . The default value is None, Represents... In the stream YAML The document does not contain an explicit document end tag . Set to True when ,YAML All in the stream YAML All documents contain an explicit document end tag .

version

Used in YAML Specify... In the document YAML Version number of , The default value is None, Means not in YAML Specify the version number in . It can be set to a tuple or list containing two elements , But the first element must be 1, Otherwise an exception will be thrown . Currently available YAML Is the version number 1.0、1.1 and 1.2.

tags

Is used to specify the YAML Labels to be included in the document . The default value is None, Indicates that no label instruction is specified . It can be set as a dictionary containing labels , The key value pairs in the dictionary correspond to different tag names and values .

4, Other methods and properties

pyyaml Support many pairs yaml Files and yaml Operation of format data

>>> dir(yaml)
['AliasEvent', 'AliasToken', 'AnchorToken', 'BaseDumper', 'BaseLoader', 'BlockEndToken', 'BlockEntryToken', 'BlockMappingStartToken', 'BlockSequenceStartToken', 
'CollectionEndEvent', 'CollectionNode', 'CollectionStartEvent', 'DirectiveToken', 'DocumentEndEvent', 'DocumentEndToken', 'DocumentStartEvent', 'DocumentStartToken',
 'Dumper', 'Event', 'FlowEntryToken', 'FlowMappingEndToken', 'FlowMappingStartToken', 'FlowSequenceEndToken', 'FlowSequenceStartToken', 'FullLoader', 'KeyToken', 
 'Loader', 'MappingEndEvent', 'MappingNode', 'MappingStartEvent', 'Mark', 'MarkedYAMLError', 'Node', 'NodeEvent', 'SafeDumper', 'SafeLoader', 'ScalarEvent', 
 'ScalarNode', 'ScalarToken', 'SequenceEndEvent', 'SequenceNode', 'SequenceStartEvent', 'StreamEndEvent', 'StreamEndToken', 'StreamStartEvent', 
 'StreamStartToken', 'TagToken', 'Token', 'UnsafeLoader', 'ValueToken', 'YAMLError', 'YAMLLoadWarning', 'YAMLObject', 'YAMLObjectMetaclass', 
 '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '__with_libyaml__',
 '_warnings_enabled', 'add_constructor', 'add_implicit_resolver', 'add_multi_constructor', 'add_multi_representer', 'add_path_resolver', 'add_representer',
 'compose', 'compose_all', 'composer', 'constructor', 'dump', 'dump_all', 'dumper', 'emit', 'emitter', 'error', 'events', 'full_load', 'full_load_all', 'io', 
 'load', 'load_all', 'load_warning', 'loader', 'nodes', 'parse', 'parser', 'reader', 'representer', 'resolver', 'safe_dump', 'safe_dump_all', 'safe_load', 
 'safe_load_all', 'scan', 'scanner', 'serialize', 'serialize_all', 'serializer', 'tokens', 'unsafe_load', 'unsafe_load_all', 'warnings']
 
 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved