yaml for python 学习笔记(python读取yaml文件相关,官网搬运)

官方文档:https://pyyaml.org/wiki/PyYAMLDocumentation
安装: pip install pyyaml
导入:import yaml
常用方法:
import yaml
document = """
a: 1
b:
c: 3
d: 4
"""
print yaml.dump(yaml.load(document))

Loader选项: BaseLoader SafeLoader FullLoader UnsafeLoader
例子:
yaml.load(input, Loader=yaml.FullLoader)
或语法糖
yaml.safe_load
yaml.full_load
yaml.unsafe_load

#load 列表:
import yaml
print(yaml.load("""
- Hesperiidae
- Papilionidae
- Apatelodidae
- Epiplemidae
"""))

# load 字典
stream = open('1.yaml', 'r',encoding='utf8') # 'document.yaml' contains a single YAML document.
print(yaml.safe_load(stream))


# load 多个文件
documents = """
---
name: The Set of Gauntlets 'Pauraegen'
description: >
A set of handgear with sparks that crackle
across its knuckleguards.
---
name: The Set of Gauntlets 'Paurnen'
description: >
A set of gauntlets that gives off a foul,
acrid odour yet remains untarnished.
---
name: The Set of Gauntlets 'Paurnimmen'
description: >
A set of handgear, freezing with unnatural cold.
"""

for data in yaml.safe_load_all(documents):
print(data)



# 创建类的实例对象 使用 !!python/object 标签
class Hero:
def __init__(self, name, hp, sp):
self.name = name
self.hp = hp
self.sp = sp

def __repr__(self):
return "%s(name=%r, hp=%r, sp=%r)" % (self.__class__.__name__, self.name, self.hp, self.sp)


a = yaml.unsafe_load('''!!python/object:__main__.Hero
name: Welthyr Syxgon
hp: 1200
sp: 0''')
print(a)
posted @ 2019-07-09 16:06  walle_ok  阅读(2211)  评论(0编辑  收藏  举报