1 yaml.dump()
- 源码:
- 作用:
将Python对象序列化为YAML流。如果stream为None,则返回生成的字符串。
- 解析:
# -*- coding:utf-8 -*-
# 作者:虫无涯
# 日期:2023/7/31
# 文件名称:pyyaml_dump.py
# 作用:yaml.dump()
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson
import yaml
data = [{
"user01": "xiaozhang", "age": 18},
{
"user02": "xiaoli", "age": 20},
{
"user03": "xiaowang", "age": 30}
]
yaml_data = yaml.dump(data)
print(yaml_data)
- 输出:
- age: 18
user01: xiaozhang
- age: 20
user02: xiaoli
- age: 30
user03: xiaowang
2 yaml.dump()
源码:
作用:
将一系列Python对象序列化为YAML流。如果stream为None,则返回生成的字符串。
- 解析:
# -*- coding:utf-8 -*-
# 作者:虫无涯
# 日期:2023/7/31
# 文件名称:pyyaml_dump_all.py
# 作用:yaml.dump_all()
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson
import yaml
data1 = [{
"user01": "xiaozhang", "age": 18},
{
"user02": "xiaoli", "age": 20},
{
"user03": "xiaowang", "age": 30}
]
data2 = {
"name1": "xiaoxiao", "age": 99}
data3 = ["beijing", "sahnghai", "guangzhou", "shenzhen"]
yaml_data = yaml.dump_all([data1, data2, data3])
print(yaml_data)
- 输出:
- age: 18
user01: xiaozhang
- age: 20
user02: xiaoli
- age: 30
user03: xiaowang
---
age: 99
name1: xiaoxiao
---
- beijing
- sahnghai
- guangzhou
- shenzhen
3 yaml.safe_dump
- 源码:
- 作用:
将Python对象序列化为YAML流。只生成基本的YAML标签。如果stream为None,则返回生成的字符串。
4 yaml.YAMLObject
- 源码:
- 作用:
一个可以将自己转储到YAML流的对象,并且从YAML流加载自身。
用元类来注册一个构造器(也就是代码里的 init() 方法),让你把yaml节点转为Python对象实例,用表示器(也就是代码里的 repr() 函数)来让你把Python对象转为yaml节点,
- 解析:
import yaml
class Person(yaml.YAMLObject):
yaml_tag = '!person'
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return '%s(name=%s, age=%d)' % (self.__class__.__name__, self.name, self.age)
james = Person('James', 20)
print (yaml.dump(james)) # Python对象实例转为yaml
lily = yaml.load('!person {name: Lily, age: 19}')
print (lily) # yaml转为Python对象实例
- 输出:
!person {
age: 20, name: James}
Person(name=Lily, age=19)