1.简介
YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言)。
官方文档:https://pyyaml.org/wiki/PyYAMLDocumentation
安装:pip3 install pyyaml
使用import导入:import yaml
2.yaml文件的读取
需要读取的yaml文件内容如下:
mysql:
host: 127.0.0.1
port: 3306
db: mysql
pwd: mysql
redis:
host: 127.0.0.1
port: 3679
db: redis
pwd: redis
读取yaml文件
import yaml
import json
yamlPath = r"E:\code\config.yml"
f = open(yamlPath,'r',encoding='utf-8')
data = yaml.load(f, Loader=yaml.FullLoader)
print(json.dumps(data, sort_keys=True, indent=4, separators=(',', ':'), ensure_ascii=False))
with语句读取
import yaml
yamlPath = r"E:\code\config.yml"
with open(file=yamlPath, mode="rb") as f:
infos = yaml.load(f, Loader=yaml.FullLoader)
print(infos)
输出:
{
"mysql":{
"db":"mysql",
"host":"127.0.0.1",
"port":3306,
"pwd":"mysql"
},
"redis":{
"db":"redis",
"host":"127.0.0.1",
"port":3679,
"pwd":"redis"
}
}
3. 文件写入
import yaml
yamlPath = r"E:\code\config.yml"
f = open(yamlPath,'a',encoding='utf-8')
data = {
"username": "zs",
"age": 18,
"hobby": ["Basketball", "eat", True]
}
yaml.dump(data, f)
再读取输出:
{
"age":18,
"hobby":[
"Basketball",
"eat",
true
],
"mysql":{
"db":"mysql",
"host":"127.0.0.1",
"port":3306,
"pwd":"mysql"
},
"redis":{
"db":"redis",
"host":"127.0.0.1",
"port":3679,
"pwd":"redis"
},
"username":"zs"
}
FAQ:
警告描述:使用 yaml.load(f)方法读取文件时,不传Loader参数会有警告
警告原因:YAML 5.1版本后弃用了yaml.load(file)这个用法,因为觉得很不安全,5.1版本之后就修改了需要指定Loader,通过默认加载器(FullLoader)禁止执行任意函数,该load函数也变得更加安全
警告解决:使用参数Loader, 取值参考:https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation