2019-04-29 python使用yaml模块例(一)

最近打算记录一下python的一些基础知识,可能比较零散,回头再重新整理。

yaml语法很简单,结构通过空格缩进来展示,列表里的项用"-"来代表,字典里的键值对用":"分隔,大致就是这样。
比如写yaml_example.yaml 文件:

name: Tony
age: 40
spouse:
    name: Judy
    age: 38
children:
    - name: Kevin
      age: 9
    - name: Bella
      age: 4

现在看下如何读取和打印,以及修改的脚本read_yaml.py(默认python3环境):

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

import sys

# sys.path.insert(0, '/home/axing/axpython/')

import yaml

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

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

运行看一下:

axing@AX:~/axpython$ ipython
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: %run read_yaml.py
  
Before:  {'name': 'Tony', 'age': 40, 'spouse': {'name': 'Judy', 'age': 38}, 'children': [{'name': 'Kevin', 'age': 9}, {'name': 'Bella', 'age': 4}]}
After:  {'name': 'Tony', 'age': 44, 'spouse': {'name': 'Judy', 'age': 38}, 'children': [{'name': 'Kevin', 'age': 10}, {'name': 'Bella', 'age': 4}]}

你可能感兴趣的:(2019-04-29 python使用yaml模块例(一))