yaml 通常用来存储数据,类似于json

安装:pip install ruamel.yaml

建一个空的yaml文件

写入数据

import os
from ruamel import yaml
# 将字典写入到yaml
data = {
'host1': '123',
'host2': 456,
'host3': {'asd': '123'},
'host4': [12, '234', ['wer', 234]],
'host5': {'asd': '123', 'eee': [12, '234', ['wer', 234]]}
} curpath = os.path.dirname(os.path.realpath(__file__)) # 当前脚本路径
yamlpath = os.path.join(curpath, "config.yaml") # 在当前脚本路径中,找到config.yaml文件 # 写入到yaml文件
with open(yamlpath, "w", encoding="utf-8") as f:
yaml.dump(data, f, Dumper=yaml.RoundTripDumper)

读取yaml文件

import os
from ruamel import yaml curpath = os.path.dirname(os.path.realpath(__file__)) # 当前脚本路径
yamlpath = os.path.join(curpath, "config.yaml") # 在当前脚本路径中,找到config.yaml文件
# 读取yaml文件
data = yaml.load(open(yamlpath, "r").read(), Loader=yaml.Loader)
print(data)
print(data['host4'][1])

封装起来以后好调用

import os
from ruamel import yaml class WRYaml:
""" yaml文件的读和写 """ def __init__(self):
""" 指定yaml文件的路径 """
self.configpath = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'config') def read_yaml(self, yaml_file='conf.yaml'):
""" 读取yaml里面里面的数据"""
try:
with open(os.path.join(self.configpath, yaml_file), "r", encoding='utf8') as f:
return yaml.load(f, Loader=yaml.Loader)
except Exception as error:
print(f'读取yaml失败,错误如下:{error}')
return False def write_yaml(self, data, yaml_file='conf.yaml', mode='w'):
""" 往yaml里面写入数据
yamlFile:yaml文件名
data:要写入的数据
mode:写入方式: w,覆盖写入, a,追加写入
将原数据读取出来,如果没有要加入的key,则创建一个,如果有,则执行key下面的数据修改
"""
try:
old_data = self.read_yaml(yaml_file) or {}
for data_key, data_value in data.items():
if not old_data.get(data_key):
old_data.setdefault(data_key, {})
for value_key, value_value in data_value.items():
old_data[data_key][value_key] = value_value
with open(os.path.join(self.configpath, yaml_file), mode, encoding="utf-8") as f:
yaml.dump(old_data, f, Dumper=yaml.RoundTripDumper)
return True
except Exception as error:
print(f'yaml文件写入失败,错误如下:\n{error}')
return False if __name__ == "__main__":
wryaml = WRYaml()
# 写入数据文件
data = {
'test': {'AAA': 134511, 'BBB': 333}
}
print(wryaml.write_yaml(yaml_file='conf.yaml', data=data))
# 读取数据文件
print(wryaml.read_yaml('conf.yaml'))

python接口自动化测试二十九:yaml配置文件的写和读的更多相关文章

  1. python接口自动化测试二十六:使用pymysql模块链接数据库

     #!/usr/bin/env python# -*- coding: utf-8 -*-# @Time    : 2018/5/28 18:51# @Author  : StalloneYang#  ...

  2. python接口自动化测试二十五:执行所有用例,并生成HTML测试报告

        import requestsimport unittest class TestQQ(unittest.TestCase):    '''测试QQ号接口'''      # 此注释将展示到测 ...

  3. python接口自动化测试二十八:连接SQL sever操作

    1.中文乱码问题: (1).文件头加上# -*- coding:utf-8 -*- 或者 #coding=utf8 (2).pymssql.connect连接串中charset是要跟你数据库的编码一样 ...

  4. python接口自动化测试二十四:上传多个附件,参数化

    # 添加多个附件参数化files = [("1.png", "1.png") ("2.png", "2.png") ]d ...

  5. python接口自动化测试二十二:文件下载

    文件下载类型: Content-Type: octets/stream   一般为文件类型:

  6. python接口自动化测试二十:函数写接口测试

    # coding:utf-8import requestsimport refrom bs4 import BeautifulSoup # s = requests.session() # 全局的s ...

  7. python接口自动化测试二十七:密码MD5加密 ''' MD5加密 ''' # 由于MD5模块在python3中被移除 # 在python3中使用hashlib模块进行md5操作 import hashlib # 待加密信息 str = 'asdas89799,.//plrmf' # 创建md5对象 hl = hashlib.md5() # Tips # 此处必须声明encode # 若写法为

    python接口自动化测试二十七:密码MD5加密   ''' MD5加密 '''# 由于MD5模块在python3中被移除# 在python3中使用hashlib模块进行md5操作import has ...

  8. python接口自动化测试二:常用操作

    url = '接口地址' r = requests.get(url)                      # 发送get请求 print(r.status_code)               ...

  9. python接口自动化测试二十三:文件上传

    # 以禅道为例: 一.创建一个类,类里面写一个登录方法: import requestsclass LoginZentao(): def __init__(self, s): # 初始化 self.s ...

随机推荐

  1. scrapy xpath、正则表达式、css选择器

    scrapy xpath XPath即为XML路径语言,它是一种用来确定XML(标准通用标记语言的子集)文档中某部分位置的语言.XPath基于XML的树状结构,提供在数据结构树中找寻节点的能力. 学习 ...

  2. js模块化的两种规范AMD和CMD

    AMD 规范在这里:https://github.com/amdjs/amdjs-api/wiki/AMDCMD 规范在这里:https://github.com/seajs/seajs/issues ...

  3. python---memcache基本使用以及内部原理

    简单使用: import memcache mc = memcache.Client(['127.0.0.1:8081','127.0.0.1:8082','127.0.0.1:8083','127. ...

  4. Access restriction: The constructor SunJCE() is not accessible 错误

    Access restriction: The type 'SunJCE' is not API (restriction on required library 'C:\Program Files\ ...

  5. CentOS6.8下Jenkins+maven+tomcat+git+shell自动构建、部署web应用环境的搭建

    参考资料:http://www.cnblogs.com/cheng95/p/6542036.html http://www.cnblogs.com/software-test/p/7068278.ht ...

  6. jdk8中奖Date转换为String格式的方法

    public static String getLocalDateStr(Date date,String formatter) { DateTimeFormatter dateTimeFormatt ...

  7. Spring面向切面编程AOP(around)实战

    spring aop的环绕通知around功能强大,我们这里就不细说,直接上代码,看着注释就能明白 需要的可以点击下载源码 1.如果使用注解的方式则需要先创建个注解类 package com.mb.a ...

  8. .net 重新注册

    今天同事问 一个IIS 的监控站点 .net 出现问题:对于windows 一般都停留在重启生效思想:然并没有生效: 于是建议重新注册.NET : 一般出现原因: 在默认安装路径 重启注册: 默认的安 ...

  9. Linux 文件日志筛选操作

    统计查看文件以及筛选日志 1.*.log 日志文件中 统计独立ip的个数: awk '{print $1}' test.log | sort | uniq | wc -l 2.#查询访问最多的前10个 ...

  10. luogu P3674 小清新人渣的本愿

    传送门 毒瘤lxl 本质是莫队,关键是怎么处理询问 这里需要开两个bitset(记为\(b1,b2\)),分别存\(x\)和\(n-x\)是否出现 对于询问1,即\(x-y=z\),由于\(y=x-z ...