• python 参数化之读取写入yaml文件


    最近自动化测试参数化使用了yaml文件进行存放,简单记录读取和写入操作

    1.读取如下yaml文件中的具体value值代码如下

    #测试环境IP、端口
    host: localhost:8080
    
    ---
    #仿真环境IP、端口
    host: localhost:8081
    def filePath(fileDir, fileName):
        return os.path.join(
            os.path.dirname(os.path.dirname(__file__)), fileDir, fileName)
    
    def readYaml(filePath):
        with open(filePath, 'r', encoding='utf-8') as f:
            return list(yaml.safe_load_all(f))
    
    fileDir = 'config'
    file = 'config.yaml'
    data = readYaml(filePath(fileDir, file))
    print(data[0]['host'])  # 打印结果为:localhost:8080

    2.写入操作,常用作上个操作返回的值将其写入yaml文件,供后面操作读取使用,yaml文件及参考代码如下:

    def set_state(docNumber, key, value):
        file_name = "test.yaml"
        with open(file_name, 'r', encoding="utf-8") as f:
            doc = list(yaml.safe_load_all(f))  # 将类型转换为list类型
            # print(list(doc))
        doc[docNumber][key] = value
        with open(file_name, 'w', encoding="utf-8") as f:
            yaml.safe_dump_all(doc, f, default_flow_style=False)
    
    set_state(value='http://122.123.124.125:8888',
              docNumber=1,
              key='host')    

    执行后的结果为:

    host: localhost:8080
    
    ---
    host: http://122.123.124.125:8888

    注意:yaml文档由“---”分隔,如果任何流(例如文件)包含多个文档,则应使用yaml.safe_load_all函数,而不是yaml.safe_load;

    写入非“---”分隔的文档时,使用yaml.safe_load、yaml.safe_dump即可,同时不需要转换类型;参考代码如下:

    def set_state(key, value):
        file_name = "test.yaml"
        with open(file_name, 'r', encoding="utf-8") as f:
            doc = yaml.safe_load(f)
    
        doc[key] = value
        with open(file_name, 'w', encoding="utf-8") as f:
            yaml.safe_dump(doc, f, default_flow_style=False)
  • 相关阅读:
    浏览器兼容模式下,上传文件问题
    计算机编程语言也是一种语言,认识的词汇越多越好
    localhost换成127.0.0.1和本机IP打不开本地项目了的问题
    mvc @html.action() 跨area调用controller 中的action
    windows server 2012 FTP连接报530 User 用户名 cannot log in home directory inaccessible的解决方法
    eCharts 数据转换json
    win10家庭版查看已连接wifi密码
    jequery动态创建form
    jsp 获取配置信息
    docker常用命令
  • 原文地址:https://www.cnblogs.com/jiahm/p/13811218.html
Copyright © 2020-2023  润新知