1. yaml 语法
    http://www.ruanyifeng.com/blog/2016/07/yaml.html

  2. 安装

pip install pyyaml
  1. yaml 样例
---UserName: AliciaPassword: pinga123 * phone: 3256TablesList:-EmployeeTable-SoftwaresList-HardwareList
...

让我们理解一下这个yaml文件

yaml文件以三个- 开始
数据可以是任意类型,比如密码是string类型,电话是number类型
缩进用于指示表列表内的项嵌套。里面的每个子项前面都有一个连字符。
yaml里面的注释用#表示
yaml 文件以…结尾,一个yaml文件可以包含多个yaml模块

  1. load yaml 文件

我们可以使用yaml.load()方法加载单个yaml. 这个方法会将yaml数据反序列化成python中的dict类型

# import pyyaml module
import yaml
from yaml.loader import SafeLoader# Open the file and load the file
with open('Userdetails.yaml') as f:data = yaml.load(f, Loader=SafeLoader)print(data)

输出如下

{'User': {'UserName': 'Alicia', 'Password': 'pinga123 *', 'phone': 3256, 'TablesList': ['haha', 'hhh']}}

对于load 方法有四种Loader参数

BaseLoader: Loads all the basic YAML scalars as Strings
SafeLoader: Loads subset of the YAML safely, mainly used if the input is from an untrusted source.
FullLoader: Loads the full YAML but avoids arbitrary code execution. Still poses a potential risk when used for the untrusted input.
UnsafeLoader: Original loader for untrusted inputs and generally used for backward compatibility.

  1. 使用 load_all() 加载多个yaml 数据

一个yaml文件可以包含多个document,每个单独的document以—开头,并以… 结尾。 我们可以一次性的读取所有数据通过使用 load_all 方法。load_all()函数解析给定的流并返回与流中的文档对应的Python对象序列。

---
User:UserName: AliciaPassword: pinga123 * phone: 3256TablesList:- haha- hhh
...
---
User:UserName: Alicia1Password: pinga123 * phone: 3256TablesList:- haha- hhh
...
# import pyyaml module
import yaml
from yaml.loader import SafeLoader# Open the file and load the file
with open('1.yaml') as f:data = list(yaml.load_all(f, Loader=SafeLoader))print(data)
  1. 将python对象写入yaml

使用yaml.dump()方法去序列化一个可以转换为dictionary的python对象并保存为yaml

import yaml# dict object
members = [{'name': 'Zoey', 'occupation': 'Doctor','hobby':[1,2,3,4,5]},{'name': 'Zaara', 'occupation': 'Dentist','hobby':[1,2,3,4,5]}]# Convert Python dictionary into a YAML document
print(yaml.dump(members))

yaml.dump() 接收两个参数, data 以及stream. data是需要序列化保存到yaml的数据,第二个参数必须是一个代开的text或者二进制文件,如果你提供了第二个参数,yaml.dump()会将数据保存到文件

import yamluser_details = {'UserName': 'Alice','Password': 'star123*','phone': 3256,'AccessKeys': ['EmployeeTable','SoftwaresList','HardwareList']}with open('UserDetails.yaml', 'w') as f:data = yaml.dump(user_details, f, sort_keys=False, default_flow_style=False)

default_flow_style: This tag is used to display the contents of the nested blocks with proper indentation. The default value is True. In that case, the values inside the nested lists are shown in the flow style but setting this tag to False will display the block style’s contents with proper indentation.
sort_keys: This tag is used to sort the keys in alphabetical order. The default value is true. By setting the tag’s value as false we can maintain the insertion order.

  1. 自定义的类序列化

Using the PyYAML module you can convert YAML into a custom Python object instead of a dictionary or built-in types. i.e., PyYAML allows you to read a YAML file into any custom Python object.

Also, You can dump instances of custom Python classes into YAML stream.

import yaml
from yaml.loader import UnsafeLoaderclass Person:def __init__(self, name, age):self.name = nameself.age = agedef __repr__(self):return "%s(name=%r, age=%r)" % (self.__class__.__name__, self.name, self.age)# Make Python Class YAML Serializable
person = Person('Jessa', 28)
yaml_obj = yaml.dump(person)# Deserialize YAML into a Custom Python Class
new_person = yaml.load(yaml_obj, Loader=UnsafeLoader)
print(new_person.name, new_person.age)

https://pynative.com/python-yaml/

python 解析yaml文件相关推荐

  1. 如何在Python中解析YAML文件

    如何在Python中解析YAML文件? #1楼 不依赖C标头的最简单,最纯净的方法是PyYaml( 文档 ): #!/usr/bin/env pythonimport yamlwith open(&q ...

  2. python修改yaml文件_Python读取yaml文件的详细教程

    yaml简介 1.yaml [ˈjæməl]: Yet Another Markup Language :另一种标记语言.yaml 是专门用来写配置文件的语言,非常简洁和强大,之前用ini也能写配置文 ...

  3. python读取yaml文件_python 怎么读取yaml文件

    yaml简介 1.yaml [ˈjæməl]: Yet Another Markup Language:另一种标记语言.yaml 是专门用来写配置文件的语言,非常简洁和强大,之前用ini也能写配置文件 ...

  4. python 对 yaml 文件操作

    python 对 yaml 文件操作 #!/usr/bin/env python # -*- encoding: utf-8 -*- """ @Introduce : p ...

  5. 【Android 逆向】使用 Python 解析 ELF 文件 ( Capstone 反汇编 ELF 文件中的机器码数据 | 完整代码示例 ) ★★★

    文章目录 一.完整代码示例 二.执行结果 三.博客资源 一.完整代码示例 使用 Python 解析 ELF 文件完整代码示例 : # coding=utf-8 # 解析 elf 文件需要导入的依赖库 ...

  6. [系统安全] 四十一.APT系列(6)Python解析PE文件并获取时间戳判断来源区域

    您可能之前看到过我写的类似文章,为什么还要重复撰写呢?只是想更好地帮助初学者了解病毒逆向分析和系统安全,更加成体系且不破坏之前的系列.因此,我重新开设了这个专栏,准备系统整理和深入学习系统安全.逆向分 ...

  7. Python解析json文件

    Python解析json文件 实现代码 import json import sysstdout = sys.stdoutwith open("company.json", &qu ...

  8. go解析yaml文件示例

    yaml文件已经成为配置的一种主要格式,因此各种语言都提供了相应的解析类库, 本文就以go语言中常用的yaml解析库 gopkg.in/yaml为例,简单展示一下如何解析yaml文件 具体代码在这里: ...

  9. python解析xml文件最好选用的模块_用Python解析XML文件

    本文翻译自:https://developer.yahoo.com/python/python-xml.html 使用Python解析XML文件 许多YDN APIs提供了JSON格式的数据输出,JS ...

最新文章

  1. 让网站具有生命与活力不仅仅是说说而已
  2. Java 压缩字符串
  3. 2015/06/08
  4. owa_util.get_cgi_env 函数参数说明.
  5. LocalReport Print with C# C#打印RDLC
  6. linux ftp解压命令 cannot fid or open,Linux环境搭建及常用shell命令集锦
  7. Bootstrap警告框
  8. post和get传值
  9. linux如何压缩数据库,linux mysql数据库压缩表空间
  10. python3第三方模块安装路径_查看python及其第三方库的版本和安装位置
  11. JavaScript的Date对象使用(1)
  12. java用不起_Java,泛型不起作用
  13. 苹果应用审核及相关问题解决方法
  14. thinkpad T430改装WiFi6网卡ax200,加装4G模块
  15. 深入理解Http请求、DNS劫持与解析
  16. 《 HTML5 》— HTML5页面元素及属性
  17. 浙大计算机学院博士毕业论文要求,浙大在读博士需要3篇SCI 论文才能毕业,清华博士却不作要求!...
  18. win10装ubuntu双系统
  19. 系统平台流量获取方式玩法
  20. 上海数字化品牌营销 whale 帷幄数字化品牌营销案例

热门文章

  1. 读书点亮生活-教育成本
  2. MSP430待机功耗问题
  3. 0成本信息差项目:地图标注该如何做?
  4. 拍照比“剪刀手”会泄露指纹信息,1.5米之内百分百还原。
  5. SRS流媒体服务器——服务器读取RTMP推流数据
  6. android打开图库,Android 7.0 以上通过系统图库打开图片的方法
  7. 创业粉去哪里引流?如何精准引流创业粉?创业粉的引流技巧
  8. 百度7天GNN学习-图与图学习中
  9. OpenCV | Mat类的copyT、clone、=赋值的区别
  10. android 带刻度的滑动条_Android自定义控件尺子 滚动刻度尺