pip install PyYAML
import yaml
yaml_file = "test.yaml"
data = yaml.load(open(yaml_file), Loader=yaml.FullLoader)
print(data)
test.yaml
文件内容
age: 10
name: J
name2: "J"
worker: True
:
后跟空格;
字符串加不加引号都可;
布尔类型,True,False;
有时候我们不喜欢使用data['name']
,偏向使用 data.name
class DotDict:
def __init__(self, d):
self.d = d
def __getattr__(self, key):
if key in self.d:
return self.d[key]
return getattr(self.d, key)
def __len__(self):
return len(self.d)
def __repr__(self):
return repr(self.d)
data = DotDict(data)
print(d.name)
print(d.keys())