yaml 库安装:http://pyyaml.org/
读取
import yaml f = open("data.yaml", "r") data = yaml.load(f) f.close() print(data) """ [ { 'name': 'PyYAML', 'status': 4, }, { 'name': 'PySyck', 'status': 5, } ] """
附:要读取的yaml文件
- name: PyYAML # 备注 status: 4 - name: PySyck status: 5
写入
import yaml new_date = { "name": "Tom", "age": 23, "sex": "man" } f = open("data1.yaml", "w") yaml.dump(new_date, f) f.close() """ {age: 23, pesonname: Tom, sex: man} """
如果要显示结构,可以增加一个参数
#写入 d={ 'person2': { 'name':'Jack', 'age':20, 'sex':'women' }, 'person1': { 'name':'Tom', 'age':29 } } f=open("newtest.yaml","w") yaml.dump(d, f, default_flow_style=False) f.close() """ person1: age: 29 name: Tom person2: age: 20 name: Jack sex: women """
关闭警告
YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated
方式一
yaml.load(input, Loader=yaml.FullLoader)
方式二
yaml.warnings({'YAMLLoadWarning': False})
方式三
PYTHONWARNINGS=ignore::yaml.YAMLLoadWarning
具体可参考
https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation