Python操作yaml文件:读取和写入详解

yaml是专门用来写配置文件的语言,简洁强大,远比JSON格式方便,yaml在python语言中有PyYAML安装包。

我这边应用场景是用来做接口自动化时,接口返回的值写入到yaml文件,然后需要用的时候直接引用即可。不如登录接口,我需获取接口返回的token,下一个接口访问时需要携带token,这时我们就可以直接读取yaml文件的值,完成脚本。

1.首先要安装PyYAML,直接安装即可
2.代码如下

import yaml


# 读取Yaml文件方法
def read_yaml(yaml_path):
    with open(yaml_path, encoding="utf-8", mode="r") as f:
        result = yaml.load(stream=f,Loader=yaml.FullLoader)
        return result

# 写入YAML文件的方法
def write_yaml(yaml_path,data):
    with open(yaml_path, encoding="utf-8", mode="w") as f:
        yaml.dump(data,stream=f,allow_unicode=True)

3.例如登录场景,如下

# coding=utf-8
import sys
import allure
from CurrencyUtils.RequestUtil import HttpUtils
import pytest
from CurrencyUtils.YamlUtil import read_yaml,write_yaml
import time
from Common.Logger import Logger

loggers = Logger().getLogger()  # 日志输出

class TestSellerLogin:
  # 卖家登录
  @allure.feature("卖家登录")
  @pytest.mark.parametrize("caseinfo", read_yaml(r"D:\wtcard-project\YamlFile\ReceptionData\SellerLogin.yaml"))#读取SellerLogin.yaml文件的内容
  def test_SellerLogin(self, caseinfo):
      print('\n-----------------卖家登录接口-------------------')
      url = caseinfo["request"]["url"]
      data = caseinfo["request"]["data"]
      data['sellerEmail'] = read_yaml(r"D:\wtcard-project\YamlFile\ReceptionData\GetValue\GetAccount.yaml")['login_account']#读取GetAccount.yaml文件的内容
      headers = caseinfo["request"]["header"]
      response = HttpUtils.http_post(headers, url, data)
      extract_value = {
          "get_access_token": response["data"]["token"]["access_token"],
          "get_userId": response["data"]["userId"],
          "get_nickName": response["data"]["nickName"]
                       }
      write_yaml(r'D:\wtcard-project\YamlFile\ReceptionData\GetValue\SellerExtract.yaml', extract_value)#get_access_token,get_userId,get_nickName写入yaml文件
      time.sleep(0.5)
      try:
          assert response['code'] == 0
          loggers.info("用户登录成功!")
      except Exception:
          loggers.info("用户登录失败!")

读取的两个yaml文件分别是


通过这种方式就可以将需要的内容写入到yaml文件,然后接口需要的时候直接读取引用即可。

物联沃分享整理
物联沃-IOTWORD物联网 » Python操作yaml文件:读取和写入详解

发表评论