Python

Py3笔记23:PyYAML

2022-09-10  本文已影响0人  _百草_

PyYAML模块是YAML解析器和生成器,即Python中使用YAML格式


0、YAML格式

数据序列化语言
通常用于配置文件,也用于数据存储或传输
支持基本数据类型:标量(如字符串、整数、浮点数)、列表、字典
推荐扩展名:.yaml
Python中2个用于YAML的模块:PyYAML、ruamel.yaml

YAML文件书写注意事项1-items.yaml
YAML文件书写注意事项1-items.yaml

1、安装

pip install pyyaml

2、使用详解

1)yaml文档读取

# 读取
import yaml  # 导入模块

with open("items.yaml") as f:
    content = yaml.load(f, Loader=yaml.FullLoader) # 加载内容
# YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. 
# Please read https://msg.pyyaml.org/load for full details.
print(content) # {'host': 'localhost', 'name': 'wlh', 'pwd': 12345, 'port': 3306}

标量值会转换为Python字典

with open("items.yaml", encoding="utf-8") as f:
    docs = yaml.load_all(f, Loader=yaml.FullLoader)  # <generator object load_all at 0x0000026A1DC9D430>
    for doc in docs:
        # doc={'host': 'localhost', 'name': 'wlh', 'pwd': 12345, 'port': 3306}
        # doc= {'cities': ['武汉', '上海', '北京', '深圳', '广州']}
        for k, v in doc.items():
            print(k, v)

2) yaml转储

n = 1  # yaml中...表示注释
print(yaml.dump(n))
s = "string"  # str
print(yaml.dump(s))
l = [1, 2, 3]
print(yaml.dump(l))
t = (4, 5, 6)
print(yaml.dump(t))
d = {"name": "百草", "age": 18}
print(yaml.dump(d, allow_unicode=True))  # 避免中文乱码

输出结果:

1
...

string
...

- 1
- 2
- 3

!!python/tuple
- 4
- 5
- 6

age: 18
name: 百草

3) yaml写入

with open("d.yaml", "w", encoding="utf-8") as f:
    yaml.dump(d, f, allow_unicode=True)
yaml写入结果

4)yaml记号
解析YAML文件时,使用较低级别的API。scan()扫描YAML流并生成扫描记号

with open("d.yaml", encoding="utf-8") as f:
    data = yaml.scan(f, Loader=yaml.FullLoader)  
    for item in data:
        print(item)

输出结果:

StreamStartToken(encoding=None)
BlockMappingStartToken()
KeyToken()
ScalarToken(plain=True, style=None, value='name')
ValueToken()
ScalarToken(plain=True, style=None, value='百草')
KeyToken()
ScalarToken(plain=True, style=None, value='age')
ValueToken()
ScalarToken(plain=True, style=None, value='18')
KeyToken()
ScalarToken(plain=True, style=None, value='class')
ValueToken()
ScalarToken(plain=True, style=None, value='一年级')
BlockEndToken()
StreamEndToken()

5)

参考

  1. Python YAML教程
  2. Python的PyYAML模块详解
  3. YAML入门教程
  4. Python Yaml写入中文乱码的问题
  5. 【Python】yaml文件的读写
上一篇下一篇

猜你喜欢

热点阅读