yaml combat in python

Like GNU, YAML is a recursive "no" name. The difference is that GNU says no to UNIX, and YAML says no to XML.
YAML is not XML.
Why not XML? because:

  • YAML is very readable.
  • YAML and scripting languages ​​interact well.
  • YAML uses the data types of the implementing language.
  • YAML has a consistent information model.
  • YAML is easy to implement.

The above 5 items are also the places where XML is insufficient. At the same time, YAML also has the following advantages of XML:
YAML can be processed based on streams;
YAML has strong expressive ability and good expansibility.

In short, YAML tries to do what XML does in a more agile way than XML.
See http://www.yaml.org for more content and specifications .
YAML syntax rules:
http://www.ibm.com/developerworks/cn/xml/x-cn-yamlintro/
http://www.yaml.org/
The syntax
structure is displayed by indenting spaces. The items in the list are represented by "-", and the key-value pairs in the dictionary are separated by ":".
This is almost all the syntax. For
example... the
general YAML file extension is .yaml. For example: yaml_example.yaml

Write yaml as a configuration script test.yaml, the following describes how to read and write yaml configuration.

start using

1. First install the yaml module

pip3 install pyyaml

2. Write the yaml configuration file yaml_example.yaml

name: junxi
age: 18
spouse:
    name: Rui
    age: 18
children:
    - name: Chen You
      age: 3
    - name: Ruo Xi
      age: 2

3. Write a python program yaml_example.py that parses yaml files

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'junxi'

import sys

# sys.path.insert(0, 'D:/program/python-腾讯课程/0-01-python其他模块学习/')

import yaml

f = open('yaml_example.yaml')
content = yaml.load(f)

print type(content)
print '修改前: ', content   # 可以看出整个Yaml配置文件是一个字典, 里面可以包含字典和列表
content['age'] = 17     # 根据Key修改对应的值
content['children'][1]['age'] = 1
print '修改后: ', content

The output of the program is:

<type 'dict'>
修改前:  {'age': 18, 'spouse': {'age': 18, 'name': 'Rui'}, 'name': 'junxi', 'children': [{'age': 3, 'name': 'Chen You'}, {'age': 2, 'name': 'Ruo Xi'}]}
修改后:  {'age': 17, 'spouse': {'age': 18, 'name': 'Rui'}, 'name': 'junxi', 'children': [{'age': 3, 'name': 'Chen You'}, {'age': 1, 'name': 'Ruo Xi'}]}

 



Author: Jun Xi,
Link : http://www.jianshu.com/p/f21b9306a68d
Source: Jianshu The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

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