想起啥记录啥之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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值