Python下解析YAML文件
Python中解析YAML文件主要使用到两个方法,load()和dump()方法,使用方式类似于Python的pickle。熟悉在Python中解析YAML文件,对使用Python做saltstack自定义插件开发时会有很大的帮助load 测试
[root@PolarSnow saltstack]# cat eg.yaml
name: Tom Smith
age: 37
spouse:
name: Jane Smith
age: 25
children:
- name: Jimmy Smith
age: 15
- name1: Jenny Smith
age1: 12[root@PolarSnow saltstack]# cat py_yaml.py
#!/usr/bin/env python
#coding=utf-8
import yamlwith open('eg.yaml', 'r') as loadfile:
print yaml.load(loadfile)[root@PolarSnow saltstack]# python py_yaml.py
{'age': 37, 'spouse': {'age': 25, 'name': 'Jane Smith'}, 'name': 'Tom Smith', 'children': [{'age': 15, 'name': 'Jimmy Smith'}, {'age1': 12, 'name1': 'Jenny Smith'}]}
关键代码
#!/usr/bin/env python
#coding=utf-8
import yaml
with open('eg.yaml', 'r') as loadfile:
print yaml.load(loadfile)
dump 测试
[root@PolarSnow saltstack]# cat eg.yaml
name: Tom Smith
age: 37
spouse:
name: Jane Smith
age: 25
children:
- name: Jimmy Smith
age: 15
- name1: Jenny Smith
age1: 12[root@PolarSnow saltstack]# cat py_yaml.py
#!/usr/bin/env python
#coding=utf-8
import yaml
with open('eg.yaml', 'r') as loadfile:
y = yaml.load(loadfile)
print y
with open('eg1.yaml','w') as dumpfile:
dumpfile.write(yaml.dump(y))
print yaml.dump(y)[root@PolarSnow saltstack]# python py_yaml.py
{'age': 37, 'spouse': {'age': 25, 'name': 'Jane Smith'}, 'name': 'Tom Smith', 'children': [{'age': 15, 'name': 'Jimmy Smith'}, {'age1': 12, 'name1': 'Jenny Smith'}]}
age: 37
children:
- {age: 15, name: Jimmy Smith}
- {age1: 12, name1: Jenny Smith}
name: Tom Smith
spouse: {age: 25, name: Jane Smith}[root@PolarSnow saltstack]# cat eg1.yaml
age: 37
children:
- {age: 15, name: Jimmy Smith}
- {age1: 12, name1: Jenny Smith}
name: Tom Smith
spouse: {age: 25, name: Jane Smith}
【Python下解析YAML文件】关键代码
#!/usr/bin/env python
#coding=utf-8
import yaml#打开一个yaml文件将其解析,再将解析后的结构再转成yaml写入到新的文件
with open('eg.yaml', 'r') as loadfile:
y = yaml.load(loadfile)
print ywith open('eg1.yaml','w') as dumpfile:
dumpfile.write(yaml.dump(y))
print yaml.dump(y)
推荐阅读
- 谎言
- #30天专注橙长计划#撑下去。
- 微服务|微服务电商项目技术全解析
- 学java还是python还是php-零基础应该选择学习|学java还是python还是php-零基础应该选择学习 java、php、前端 还是 python()
- 黄昏下的那点事
- 用Excel学理财(0)(在开始学习之前,请收下这份提示)
- 计算稍有进步
- 冷笑话
- 渐入佳境
- 融云入选优秀厂商!|《2022中国信创生态市场研究及选型评估报告》(附下载)发布