python解析.yml/.yaml文件--pyyaml模块(第三方)


第一part:YAML文件介绍


 1.YAML文件的定义:是一种比XML和JSON更轻的文件格式,也更简单更强大,它可以通过缩进来表示结构,是不是与Python使用有异曲同工之处;

2.YAML文件的特点:

1)YAML的可读性好。

2)YAML和脚本语言的交互性好。

3)YAML使用实现语言的数据类型。

其官网描述:YAML语言的设计目标,就是方便人类读写。

3.YAML文件规则:

1)区分大小写;

2)使用缩进表示层级关系;

3)使用空格键缩进,而非Tab键缩进

4)缩进的空格数目不固定,只需要相同层级的元素左侧对齐;

5)文件中的字符串不需要使用引号标注,但若字符串包含有特殊字符则需用引号标注;

6)注释标识为#

4.YAML文件数据结构

 

1)对象:键值对的集合(简称 "映射或字典")
2)键值对用冒号 “:” 结构表示,冒号与值之间需用空格分隔

3)数组:一组按序排列的值(简称 "序列或列表")
数组前加有 “-” 符号,符号与值之间需用空格分隔

4)纯量(scalars):单个的、不可再分的值(如:字符串、bool值、整数、浮点数、时间、日期、null等)
None值:可用null、可 ~ 表示

 


 第二part:yaml对象与python对象对应表


 官网:https://pyyaml.org/wiki/PyYAMLDocumentation

YAML tags and Python types

The following table describes how nodes with different tags are converted to Python objects.

YAML tag Python type
Standard YAML tags  
!!null None
!!bool bool
!!int int or long (int in Python 3)
!!float float
!!binary str (bytes in Python 3)
!!timestamp datetime.datetime
!!omap!!pairs list of pairs
!!set set
!!str str or unicode (str in Python 3)
!!seq list
!!map dict
Python-specific tags  
!!python/none None
!!python/bool bool
!!python/bytes (bytes in Python 3)
!!python/str str (str in Python 3)
!!python/unicode unicode (str in Python 3)
!!python/int int
!!python/long long (int in Python 3)
!!python/float float
!!python/complex complex
!!python/list list
!!python/tuple tuple
!!python/dict dict
Complex Python tags  
!!python/name:module.name module.name
!!python/module:package.module package.module
!!python/object:module.cls module.cls instance
!!python/object/new:module.cls module.cls instance
!!python/object/apply:module.f value of f(...)


 第三part:Python读取yaml文件的数据


 python对yaml文件的操作,需要安装第三方模块pyyaml,安装方式有两种:

第一种:命令行安装--》pip install pyyaml  

第二种:pychram安装---》pycharm--project---project interpreter中搜索pyyaml进行安装

 python读取yaml文件的规则:python通过open方式读取文件数据,再通过yaml.load()函数将数据转化为列表或字典;

整体代码为:

import yaml
with open("data3.yaml",'r', encoding="utf-8") as fp:
result=fp.read()
print(type(result))
get_result= yaml.load(result,Loader=yaml.SafeLoader)
print(get_result,type(get_result))

执行结果,如下:



第四part:yaml文件对应python类型的详细写法:

 1.yaml键值对:即python中字典:

#yaml文件的写法:

username: huangshan
password: 123456

#python解析yaml文件后获取的数据:

{'usrname': 'wood', 'password': 123456}
yaml文件中内容为“键值对'嵌套"键值对"


2 .yaml键值对嵌套:即python中字典嵌套字典:

#yaml文件的写法:

usr1:
name: a
psw: 123
usr2:
name: b
psw: 456

#python解析yaml文件后获取的数据:


{'usr1': {'name': 'a', 'psw': 123}, 'usr2': {'name': 'b', 'psw': 456}}


3.yaml文件中“键值对”中嵌套“列表:

# yaml键值对中嵌套数组


usr3:
- a
- b
- c
usr4:
- d

#python解析yaml文件后获取的数据:

 

{'usr3': ['a', 'b', 'c'], 'usr4': ['d']}

 

4. yaml键值对中嵌套数组:

# yaml键值对中嵌套数组

usr3:
- a
- b
- c
usr4:
- d

 

#python解析yaml文件后获取的数据:


{'usr3': ['a', 'b', 'c'], 'usr4': ['d']}

5.yaml文件数据为数组:

(1)yaml文件中内容为数组

# yaml数组:


- a
- b
- 5


#python解析yaml文件后获取的数据:


['a', 'b', 5]


(2)yaml文件“数组”中嵌套“键值对”

# yaml"数组"中嵌套"键值对":


- usr1: aaa
- psw1: 111
usr2: bbb
psw2: 222


python解析yaml文件后获取的数据:

[{'usr1': 'aaa'}, {'psw1': 111, 'usr2': 'bbb', 'psw2': 222}]


6.yaml文件中基本数据类型:

# 纯量定义


s_val: wood # 字符串:{'s_val': 'wood'}
spec_s_val: "name\n" # 特殊字符串:{'spec_s_val': 'name\n'
num_val: 30.14 # 数字:{'num_val': 30.14}
bol_val: true # 布尔值:{'bol_val': True}
nul_val: null # null值:{'nul_val': None}
nul_val1: ~ # null值:{'nul_val1': None}
date_val: 2020-06-01 # 日期值:{'date_val': datetime.date(2020, 06, 01)}

7.yaml文件中引用:

#yaml文件中内容

animal: &animal tiger

test: *animal

#python读取的数据

{'animal': 'tiger', 'test': 'tiger'}

 


 第五part:python读取一个yaml文件中多个文档


 1. 多个文档在一个yaml文件,使用 --- 分隔方式来分段

# 分段yaml文件中多个文档
---
student1: zhangsan
age: 18
---
student2: lisi
age: 20

 

2. python脚本读取一个yaml文件中多个文档方法
python获取yaml数据时需使用load_all函数来解析全部的文档,再从中读取对象中的数据
# yaml文件中含有多个文档时,分别获取文档中数据,整体代码:

import yaml
with open('data3.yaml', 'r', encoding="utf-8") as file:
file_data = file.read()
all_data = yaml.load_all(file_data, Loader=yaml.SafeLoader)
for data in all_data:
print(data)


执行结果为:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM