Python读取YAML文件过程详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python读取YAML文件过程详解

  2021-04-02 我要评论

这篇文章主要介绍了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]
}
您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们