网络编程
位置:首页>> 网络编程>> Python编程>> Python读取YAML文件过程详解

Python读取YAML文件过程详解

作者:MilesMa  发布时间:2021-04-21 07:12:25 

标签:Python,读取,YAML,文件

这篇文章主要介绍了Python读取YAML文件过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

YAML语法 学习手册

Python读取方法:


import yaml
with open('demo1.yaml', 'r', encoding='utf-8') as f:
 file_content = f.read()
content = yaml.load(file_content, yaml.FullLoader)
print(content)

demo1.yaml


- 123             # int
- 3.14            # float
- true            # bool,不区分大小写
- False            # bool
- string           # 字符串
- ''             # 空字符串
- ~              # ~代表 null,Python中的 None
-               # 同上
- 2019-12-12         # date
- 2019-12-12T14:59:59+08:00  # datetime
- name: Miles         # dict
age: 22

使用以上方法后的结果是一个列表,手动换行了方便阅读:


[
123,
3.14,
True,
False,
'string',
'',
None,
None,
datetime.date(2019, 12, 12),
datetime.datetime(2019, 12, 12, 6, 59, 59),
{'name': 'Miles', 'age': 22}
]

demo2.yaml


name: Miles
age: 18
single: true
dream: ~
lucky number:
- 8
- 9
- 12

这种形式经过方法读取是一个字典:


{
'name': 'Miles',
'age': 18,
'single': True,
'dream': None,
'lucky number':[8, 9, 12]
}

来源:https://www.cnblogs.com/milesma/p/12112087.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com