python with open as yaml_python怎么解析yaml文件?
首先安裝PyYAML:
pip install PyYAML
然后你需要自定義tag,代碼如下
import yaml
class HaHa(yaml.YAMLObject):
yaml_tag = '!haha'
def __init__(self, note):
self.note = note
def __repr__(self):
return "%s(note=%r)" % (self.__class__.__name__, self.note)
class Description(yaml.YAMLObject):
yaml_tag = '!description'
def __init__(self, age, home):
self.age = age
self.home = home
def __repr__(self):
return "%s(age=%r, home=%r)" % (
self.__class__.__name__, self.age, self.home)
獲取home的值:
if __name__ == '__main__':
with open('test.yaml', 'r') as f:
yaml_data = yaml.load(f)
print(yaml_data)
print(yaml_data.get('massage').home)
輸出:
{'name': 'MyName !!', 'name2': HaHa(note='name2'), 'massage': Description(age=18, home=['SH', 'BJ', 'GZ'])}
['SH', 'BJ', 'GZ']
test.yaml是你上面貼出來的數據
總結
以上是生活随笔為你收集整理的python with open as yaml_python怎么解析yaml文件?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql中用户管理_mysql 中用户
- 下一篇: python读取二进制数据中的while