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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM