[918]python使用yaml模块

yaml文件介绍

yaml是一个专门用来写配置文件的语言。

1. yaml文件规则
  • 区分大小写;
  • 使用缩进表示层级关系;
  • 缩进时不允许使用Tab键,只允许使用空格;
  • 缩进的空格数目不固定,只需要相同层级的元素左侧对齐;
  • 文件中的字符串不需要使用引号标注,但若字符串包含有特殊字符则需用引号标注;
  • #表示注释,从这个字符一直到行尾,都会被解析器忽略,这个和python的注释一样
2. yaml文件数据结构
  • 对象:键值对的集合(简称 “映射或字典”)
    键值对用冒号 “:” 结构表示,冒号与值之间需用空格分隔
  • 数组:一组按序排列的值(简称 “序列或列表”)
    数组前加有 “-” 符号,符号与值之间需用空格分隔
  • 纯量(scalars):单个的、不可再分的值(如:字符串、bool值、整数、浮点数、时间、日期、null等)
    None值可用null可 ~ 表示

python中读取yaml配置文件

1. 前提条件

python中读取yaml文件前需要安装pyyaml和导入yaml模块:

  • 使用yaml需要安装的模块为pyyaml(pip3 install pyyaml);
  • 导入的模块为yaml(import yaml)
2. 读取yaml文件数据

python通过open方式读取文件数据,再通过load函数将数据转化为列表或字典;

import yaml
import os

def get_yaml_data(yaml_file):
    # 打开yaml文件
    print("***获取yaml文件数据***")
    file = open(yaml_file, 'r', encoding="utf-8")
    file_data = file.read()
    file.close()
    
    print(file_data)
    print("类型:", type(file_data))

    # 将字符串转化为字典或列表
    print("***转化yaml数据为字典或列表***")
    data = yaml.load(file_data)
    print(data)
    print("类型:", type(data))
    return data
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "config.yaml")
get_yaml_data(yaml_path)

"""
***获取yaml文件数据***
# yaml键值对:即python中字典
usr: my
psw: 123455
类型:<class 'str'>
***转化yaml数据为字典或列表***
{'usr': 'my', 'psw': 123455}
类型:<class 'dict'>
"""
3. yaml文件数据为键值对

(1)yaml文件中内容为键值对:

# yaml键值对:即python中字典
usr: my
psw: 123455
s: " abc\n"

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

{'usr': 'my', 'psw': 123455, 's': ' abc\n'}

(2)Yaml 也允许另一种写法,将所有键值对写成一个行内对象。

hash: { name: Steve, foo: bar }

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

{ hash: { name: 'Steve', foo: 'bar' } }

(3)yaml文件中内容为“键值对’嵌套"键值对"

# yaml键值对嵌套:即python中字典嵌套字典
usr1:
  name: a
  psw: 123
usr2:
  name: b
  psw: 456

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

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

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

# yaml键值对中嵌套数组
usr3:
  - a
  - b
  - c
usr4:
  - b

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

{'usr3': ['a', 'b', 'c'], 'usr4': ['b']}
4. yaml文件数据为数组

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

# yaml数组
- a
- b
- 5

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

['a', 'b', 5]

(2)数据结构的子成员是一个数组,则可以在该项下面缩进一个空格。

-
 - Cat
 - Dog
 - Goldfish

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

[ [ 'Cat', 'Dog', 'Goldfish' ] ]

(3)数组也可以采用行内表示法。

animal: [Cat, Dog]

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

{ animal: [ 'Cat', 'Dog' ] }

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

# yaml"数组"中嵌套"键值对"
- usr1: aaa
- psw1: 111
  usr2: bbb
  psw2: 222

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

[{'usr1': 'aaa'}, {'psw1': 111, 'usr2': 'bbb', 'psw2': 222}]
5. 复合结构

对象和数组可以结合使用,形成复合结构。

languages:
 - Ruby
 - Perl
 - Python 
websites:
 YAML: yaml.org 
 Ruby: ruby-lang.org 
 Python: python.org 
 Perl: use.perl.org

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

{ languages: [ 'Ruby', 'Perl', 'Python' ],
  websites: 
   { YAML: 'yaml.org',
     Ruby: 'ruby-lang.org',
     Python: 'python.org',
     Perl: 'use.perl.org' } }
6. yaml文件中基本数据类型:

纯量是最基本的、不可再分的值

字符串
布尔值
整数
浮点数
Null
时间
日期

# 纯量
s_val: name              # 字符串:{'s_val': 'name'}
spec_s_val: "name\n"    # 特殊字符串:{'spec_s_val': 'name\n'
num_val: 31.14          # 数字:{'num_val': 31.14}
bol_val: true           # 布尔值:{'bol_val': True}
nul_val: null           # null值:{'nul_val': None}
nul_val1: ~             # null值:{'nul_val1': None}
time_val: 2018-03-01t11:33:22.55-06:00     # 时间值:{'time_val': datetime.datetime(2018, 3, 1, 17, 33, 22, 550000)}
date_val: 2019-01-10    # 日期值:{'date_val': datetime.date(2019, 1, 10)}
字符串

字符串是最常见,也是最复杂的一种数据类型。

字符串默认不使用引号表示

str: 这是一行字符串

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

{ str: '这是一行字符串' }

如果字符串之中包含空格或特殊字符,需要放在引号之中

str: '内容: 字符串'

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

{ str: '内容: 字符串' }

单引号和双引号都可以使用,双引号不会对特殊字符转义

s1: '内容\n字符串'
s2: "内容\n字符串"

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

{ s1: '内容\\n字符串', s2: '内容\n字符串' }

单引号之中如果还有单引号,必须连续使用两个单引号转义

str: 'labor''s day'

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

{ str: 'labor\'s day' }

字符串可以写成多行,从第二行开始,必须有一个单空格缩进。换行符会被转为空格。

str: 这是一段
  多行
  字符串

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

 { str: '这是一段 多行 字符串' }

多行字符串可以使用|保留换行符,也可以使用>折叠换行。

this: |
  Foo
  Bar
that: >
  Foo
  Bar

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

 { this: 'Foo\nBar\n', that: 'Foo Bar\n' }

+表示保留文字块末尾的换行,-表示删除字符串末尾的换行。

s1: |
  Foo
 
s2: |+
  Foo
 
 
s3: |-
  Foo

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

 { s1: 'Foo\n', s2: 'Foo\n\n\n', s3: 'Foo' }

字符串之中可以插入 HTML 标记。

message: |
 
  <p style="color: red">
    段落
  </p>

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

 { message: '\n<p style="color: red">\n  段落\n</p>\n' }
7.YAML 允许使用两个感叹号,强制转换数据类型
e: !!str 123
f: !!str true

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

{ e: '123', f: 'true' }
8. yaml文件中引用

锚点&和别名*,可以用来引用。

defaults: &defaults
  adapter:  postgres
  host:     localhost
 
development:
  database: myapp_development
  <<: *defaults
 
test:
  database: myapp_test
  <<: *defaults

等同于下面的代码

defaults:
  adapter:  postgres
  host:     localhost
 
development:
  database: myapp_development
  adapter:  postgres
  host:     localhost
 
test:
  database: myapp_test
  adapter:  postgres
  host:     localhost

&用来建立锚点(defaults),<<表示合并到当前数据,*用来引用锚点。

下面是另一个例子

- &showell Steve 
- Clark 
- Brian 
- Oren 
- *showell

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

[ 'Steve', 'Clark', 'Brian', 'Oren', 'Steve' ]

python中读取多个yaml文档

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

如:yaml文件中数据

# 分段yaml文件中多个文档
---
animal1: dog
age: 2
---
animal2: cat
age: 3
  1. python脚本读取一个yaml文件中多个文档方法

python获取yaml数据时需使用load_all函数来解析全部的文档,再从中读取对象中的数据

# yaml文件中含有多个文档时,分别获取文档中数据
def get_yaml_load_all(yaml_file):
    # 打开yaml文件
    file = open(yaml_file, 'r', encoding="utf-8")
    file_data = file.read()
    file.close()
    all_data = yaml.load_all(file_data)
    for data in all_data:
        print(data)
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "config.yaml")
get_yaml_load_all(yaml_path)
"""结果
{'animal1': 'dog', 'age': 2}
{'animal2': 'cat', 'age': 3}
"""

python对象生成yaml文档

  1. 直接导入yaml(即import yaml)生成的yaml文档

通过yaml.dump()方法不会将列表或字典数据进行转化yaml标准模式,只会将数据生成到yaml文档中

# 将python对象生成yaml文档
import yaml
def generate_yaml_doc(yaml_file):
    py_object = {'school': 'zhang',
                 'students': ['a', 'b']}
    file = open(yaml_file, 'w', encoding='utf-8')
    yaml.dump(py_object, file)
    file.close()
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "generate.yaml")
generate_yaml_doc(yaml_path)
"""结果
school: zhang
students: [a, b]
"""
  1. 使用ruamel模块中的yaml方法生成标准的yaml文档

(1)使用ruamel模块中yaml前提条件

  • 使用yaml需要安装的模块:ruamel.yaml(pip3 install ruamel.yaml);
  • 导入的模块:from ruamel import yaml

(2)ruamel模块生成yaml文档

def generate_yaml_doc_ruamel(yaml_file):
    from ruamel import yaml
    py_object = {'school': 'zhang',
                 'students': ['a', 'b']}
    file = open(yaml_file, 'w', encoding='utf-8')
    yaml.dump(py_object, file, Dumper=yaml.RoundTripDumper)
    file.close()
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "generate.yaml")
generate_yaml_doc_ruamel(yaml_path)
"""结果
school: zhang
students:
- a
- b
"""

(3)ruamel模块读取yaml文档

# 通过from ruamel import yaml读取yaml文件
def get_yaml_data_ruamel(yaml_file):
    from ruamel import yaml
    file = open(yaml_file, 'r', encoding='utf-8')
    data = yaml.load(file.read(), Loader=yaml.Loader)
    file.close()
    print(data)
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "dict_config.yaml")
get_yaml_data_ruamel(yaml_path)

文档

参考:https://www.jianshu.com/p/eaa1bf01b3a6
https://blog.csdn.net/yongwan5637/article/details/80338422
https://www.cnblogs.com/klb561/p/10085328.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小董

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值