yaml的使用记录
一、锚点的使用
xxx.yaml
test: &test
pwd: test123
host: localhost
dev:
user: devuser
<<: *test
等同于:
test:
pwd: test123
host: localhost
dev:
user: devuser
pwd: test123
host: localhost
PS:& 给test建立锚点,dev下的 << 表示合并到当前数据,* 用来引用锚点
二、YAML强制转换类型
### YAML使用(双感叹号+目标类型)来强制转换类型
!!str 10086 # 整数转为字符串
!!int '0' # 字符串转为整数
!!str 10086.010 # 浮点数转为字符串
.....
三、操作YAML(读、写、删)
1.先导入包:pip install pyyaml
#!/usr/bin/python
# -*- coding: UTF-8 -*
import os
import yaml
from config import setting
class YamlUtil:
def __init__(self):
self.file_path = setting.extract_file # 这里我定义的是公共文件路径
self.user_file_path = setting.user_extract_file # 这里我定义的是某个用户的文件路径
def clear_yaml(self):
"""清空yaml数据"""
with open(self.file_path, encoding="utf-8", mode="w") as f:
f.truncate()
def read_yaml(self):
"""读取yaml数据"""
with open(self.file_path, encoding="utf-8") as f:
return yaml.safe_load(f)
def write_yaml(self, data):
"""写入yaml数据"""
# mode="w" 是覆盖 mode="a+" 是追加写入
with open(self.file_path, encoding="utf-8", mode="a+") as f:
yaml.safe_dump(data, f, allow_unicode=True)
if __name__ == '__main__':
# 使用
YamlUtil().clear_yaml()
YamlUtil().read_yaml()
data = dict()
data['user'] = 'xiyouji'
YamlUtil().write_yaml(data)