首页 > 编程语言 >python操作yaml

python操作yaml

时间:2024-01-29 19:44:20浏览次数:28  
标签:__ utf python res yaml file 操作 data

 

补充:yaml语法

详见:yaml语法

 

yaml应用场景

1、保存测试数据

2、也可以保存自动化测试中的关联数据 

 

安装yaml模块

pip install pyyaml==5.4.1

 

读取yaml数据

读取数据:load()或者full_load() ,返回一个对象

用例数据:case.yaml

- caseId: 1
  apiName: register
  describe: 注册
  url: /qzcsbj/user/register
  requestType: post
  headers: {'Content-Type':'application/json'}
  cookies:
  parameters: {"username":"qzcsbj","password":"123456","realName":"韧","sex":"1","birthday":"1989-01-16","phone":"13500000006","utype":"1","adduser":"韧"}
  uploadFile:
  initSql: [{"sqlNo":"1","sql":"delete from user where username = 'qzcsbj';"}]
  globalVariables:
  assertFields: $.msg=注册成功;

- CaseId: 2
  ApiName: login
  Describe: 登录
  Url: /qzcsbj/user/login
  RequestType: post
  Headers: {"Content-Type":"application/json"}
  Cookies:
  Parameters: {"username":"qzcsbj", "password":"123456"}
  UploadFile:
  InitSql:
  GlobalVariables: token=$.data.token;
  AssertFields: $.msg=登录成功;

  

实现: 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 公众号 : 全栈测试笔记
# 作者: 韧
# wx: ren168632201
# 描述:<>

import os
import yaml

def read_data_from_yaml(file_path):
    f = open(file_path, "r", encoding="utf-8")
    # res = yaml.load(f, yaml.FullLoader)
    res = yaml.full_load(f)
    return res

if __name__ == '__main__':
    cases = read_data_from_yaml(os.getcwd() + r'\case.yaml')
    print(cases)

  

结果:

 

读取数据:load_all()或者full_load_all(),生成一个迭代器

用例数据:case2.yaml

caseId: 1
apiName: register
describe: 注册
url: /qzcsbj/user/register
requestType: post
headers: {'Content-Type':'application/json'}
cookies:
parameters: {"username":"qzcsbj","password":"123456","realName":"韧","sex":"1","birthday":"1989-01-16","phone":"13500000006","utype":"1","adduser":"韧"}
uploadFile:
initSql: [{"sqlNo":"1","sql":"delete from user where username = 'qzcsbj';"}]
globalVariables:
assertFields: $.msg=注册成功;

---

CaseId: 2
ApiName: login
Describe: 登录
Url: /qzcsbj/user/login
RequestType: post
Headers: {"Content-Type":"application/json"}
Cookies:
Parameters: {"username":"qzcsbj", "password":"123456"}
UploadFile:
InitSql:
GlobalVariables: token=$.data.token;
AssertFields: $.msg=登录成功;

 

文件包含几块yaml

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 公众号 : 全栈测试笔记
# 作者: 韧
# wx: ren168632201
# 描述:<>

import os
import yaml

def read_data_from_yaml(file_path):
    f = open(file_path, "r", encoding="utf-8")
    # res = yaml.load_all(f, yaml.FullLoader)
    res = yaml.full_load_all(f)
    return res

if __name__ == '__main__':
    cases = read_data_from_yaml(os.getcwd() + r'\case2.yaml')
    print(cases)
    for case in cases:
        print(case)

  

结果:

 

写入yaml数据

写入数据:yaml.dump(),将一个python对象生成为yaml文档

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 公众号 : 全栈测试笔记
# 作者: 韧
# wx: ren168632201
# 描述:<>

import yaml


if __name__ == '__main__':
    data = {"name": "韧", "age": "22", "hobbies": ["running", "swimming", "football"]}
    print(yaml.dump(data, allow_unicode=True))

  

结果:

 

写入到文件

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 公众号 : 全栈测试笔记
# 作者: 韧
# wx: ren168632201
# 描述:<>

import os
import yaml

def read_data_from_yaml(file_path):
    with open(file_path, "r", encoding="utf-8") as f:
        # res = yaml.load(f, yaml.FullLoader)
        res = yaml.full_load(f)
        return res

def write_data_to_yaml(data, data_file):
    # a+表示append
    with open(data_file, "w", encoding="utf-8") as f:
        yaml.dump(data, f, allow_unicode=True)

if __name__ == '__main__':
    data = {"name": "韧", "age": "22", "hobbies": ["running", "swimming", "football"]}
    data_file = os.getcwd() + r"/test.yaml"
    write_data_to_yaml(data, data_file)
    cases = read_data_from_yaml(data_file)
    print(cases)

 

结果:

文件内容

 

列表数据写入文件

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 公众号 : 全栈测试笔记
# 作者: 韧
# wx: ren168632201
# 描述:<>

import os
import yaml

def read_data_from_yaml(file_path):
    with open(file_path, "r", encoding="utf-8") as f:
        # res = yaml.load(f, yaml.FullLoader)
        res = yaml.full_load(f)
        return res

def write_data_to_yaml(data, data_file):
    # a+表示append
    with open(data_file, "w", encoding="utf-8") as f:
        yaml.dump(data, f, allow_unicode=True)

if __name__ == '__main__':
    data1 = {"name": "韧", "age": "22", "hobbies": ["running", "swimming", "football"]}
    data2 = {"name": "qzcsbj", "age": "23", "hobbies": ["reading", "walking"]}
    data_file = os.getcwd() + r"/test.yaml"
    write_data_to_yaml([data1,data2], data_file)
    cases = read_data_from_yaml(data_file)
    print(cases)

  

结果:

文件内容

 

优化:数据合并

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 公众号 : 全栈测试笔记
# 作者: 韧
# wx: ren168632201
# 描述:<>

import os
import yaml

def read_data_from_yaml(file_path):
    with open(file_path, "r", encoding="utf-8") as f:
        # res = yaml.load(f, yaml.FullLoader)
        res = yaml.full_load(f)
        return res

def write_data_to_yaml(data, data_file):
    # a+表示append
    with open(data_file, "w", encoding="utf-8") as f:
        yaml.dump(data, f, allow_unicode=True)

if __name__ == '__main__':
    data = [{"name": "韧", "age": "22", "hobbies": ["running", "swimming", "football"]},{"name": "qzcsbj", "age": "23", "hobbies": ["reading", "walking"]}]
    data_file = os.getcwd() + r"/test.yaml"
    write_data_to_yaml(data, data_file)
    cases = read_data_from_yaml(data_file)
    print(cases)

 

写入数据:yaml.dump_all(),将多个段输出到一个文件中

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 公众号 : 全栈测试笔记
# 作者: 韧
# wx: ren168632201
# 描述:<>

import os
import yaml

def read_data_from_yaml(file_path):
    f = open(file_path, "r", encoding="utf-8")
    # res = yaml.load_all(f, yaml.FullLoader)
    res = yaml.full_load_all(f)
    return res

def write_data_to_yaml(data, data_file):
    # a+表示append
    with open(data_file, "w", encoding="utf-8") as f:
        yaml.dump_all(data, f, allow_unicode=True)

if __name__ == '__main__':
    data1 = {"name": "韧", "age": "22", "hobbies": ["running", "swimming", "football"]}
    data2 = {"name": "qzcsbj", "age": "23", "hobbies": ["reading", "walking"]}
    data_file = os.getcwd() + r"/test.yaml"
    write_data_to_yaml([data1,data2], data_file)
    cases = read_data_from_yaml(data_file)
    print(cases)
    for case in cases:
        print(case)

  

结果:

文件中加了---分隔符

 

清空yaml数据

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 公众号 : 全栈测试笔记
# 作者: 韧
# wx: ren168632201
# 描述:<>

import os

def clear_yaml(data_file):
    f = open(data_file, "w", encoding="utf-8")
    f.truncate()

if __name__ == '__main__':
    data_file = os.getcwd() + r"/test.yaml"
    clear_yaml(data_file)

 

【bak】

 

 

标签:__,utf,python,res,yaml,file,操作,data
From: https://www.cnblogs.com/uncleyong/p/17994122

相关文章

  • 详解module ‘yaml‘ has no attribute ‘FullLoader‘
    详解module'yaml'hasnoattribute'FullLoader'在使用Python中的YAML库进行解析操作时,可能会遇到类似于module'yaml'hasnoattribute'FullLoader'的错误。这个错误通常是由于不同版本的PyYAML库之间的差异导致的。在本篇文章中,我们将详细解释这个问题的原因,并提供一些解决方......
  • python 14
    1.代码规范程序员写代码四有规范的,不只是实现功能而已。1.1名称在python开发过程中会创建文件夹/文件/变量等,这些在命名有一些潜规则(编写代码时也要注意pep8规范)文件夹,小写&小写下划线连接,例如:commands,data_utils等。文件,小写&小写下划线连接,例如:page.py,db_convert.p......
  • python之常用标准库-configparser
    configparser主要用于生成和修改常见配置文档,所以常见的操作为读和写1.写定义参数变量,赋值直接赋值法conf['test_default']={'test_line1':'test_line1'}通过增加section,set赋值法conf.add_section('test')conf.set('test','test_line1',�......
  • docker-compose.yaml相关
    docker-compose.yaml相关Compose和Docker兼容性:Compose文件格式有3个版本,分别为1,2.x和3.x目前主流的为3.x其支持docker1.13.0及其以上的版本常用参数:version#指定compose文件的版本services#定义所有的service信息,......
  • python中get请求传参方式的写法
    get请求分为两大类:无参数和有参数1.无参数2.有参数2.1参数较少2.2参数较多-字典形式2.3参数较多-列表+元祖形式......
  • python版本管理Dynaconf模块
    示例代码importosimportsysfrompathlibimportPathfromdynaconfimportDynaconf_BASE_DIR=Path(__file__).parent.parent_CONFIG_DIR=_BASE_DIR/'config'LOG_DIR=_BASE_DIR/'files'/'logs'TOKEN_FILE=_BASE_DIR/�......
  • 如何在 Python 中使用 jieba 库来进行关键词提取
    jieba是一个流行的中文分词库,通过简单的几行代码,您就可以轻松地使用jieba库来提取中文文本中的关键词。本文将介绍jieba库的安装方法以及关键词提取的示例代码,并希望对您有所帮助。正文:1.安装jieba库:首先,我们需要安装jieba库。可以使用以下命令来安装jieba库:```pipinstalljieba......
  • python日志模块logging
    示例代码#导入日志模块importloggingimportlogging.configfromconfigimportLOG_DIR,settingsdefconfig_logging():#定义日志配置方法config_dict={#定义日志配置字典'version':1,'disable_existing_loggers':False,'......
  • Python中/与//的区别是什么?其如何使用?
    在学习Python或者使用Python进行工作的时候,大家应该都看到过“/”和“//”,它们是Python算术运算符中比较常用的两个运算符,那么Python语言中/与//的区别是什么?如果你还不清楚,这篇文章千万不要错过。Python语言中/与//的区别是什么?在Python中/表示浮点整除法,返回浮点结......
  • 四、python数据类型的性能
    四、python数据类型的性能比较列表list和字典dict两种内置数据类型上各种操作大O数量级两种都属于容器,都是可变类型。类型listdict索引自然数i不可变类型值key添加append/extend/insertb[k]=v删除pop/removepop更新a[i]=vb[k]=v正查a[i]/a[i......