Operation of yaml file

Introduction to yaml basic grammar:
* The design goal of the YAML language (pronounced /ˈjæməl/) is to facilitate human reading and writing. It is essentially a general-purpose data serialization format. *

Its basic grammar rules:

  • case sensitive, case sensitive
  • Use indentation to indicate hierarchical relationship Tab key is not allowed when indenting, only spaces are allowed. The number of spaces indented is not important, as long as the elements of 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.

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 ​​arranged in order, also known as a sequence (sequence) / list (list)
  • scalars: single, indivisible values

Python operates yaml files
1. Install yaml: pip install yaml
2. Call yaml.safe_load() method
For example:

# 这是一个yaml练习文件
practice :
  dec : "身份证号码查询 "
  parameters :
    -
      test: 123456
  test : "python"
else : "java"

Perform python read operation, the code is as follows:

def open_yaml():
    try:
        with open(file=r"E:\PythonInterface\data\yaml\practice.yaml", encoding="utf-8")as sun:
            result = yaml.safe_load(stream=sun)
            return result
    except FileNotFoundError as e:
        return 0


if __name__ == '__main__':
    info = open_yaml()
    print(info)

The result of the operation is as follows:
{'practice':
{'dec': 'ID card number query',
'parameters':
[{'test1': 123456, 'test2': 123789}], # test1 and parameters are separated by - so- The following are all list types
'test': 'python'},
'else': 'java'}#else is at the same level as practice, without spaces

Converting to json format output can clearly see the format:
{ "practice": { "dec": "ID card number query", "parameters": [ #list { "test1": 123456 } ], "test": "python } , "else": "java" }










...to be continued...

Guess you like

Origin blog.csdn.net/qq_40267002/article/details/113310775