Python实用脚本

1、读取yaml文件:
test.yaml:

testinfo:
  - testcase1: test1
    test2: test2
  - testcase2: test1
    test2: test2

test.py:

import yaml

def load_yaml_file(yaml_file):
    try:
        with open(yaml_file, encoding='utf-8') as f:
            file_stream = yaml.load(f)
            return file_stream
    except FileNotFoundError:
        pass

if __name__=='__main__':
    file_content=load_yaml_file(r'test.yaml')
    print(file_content.get('testinfo'))

输出:

[{'test2': 'test2', 'testcase1': 'test1'}, {'testcase2': 'test1', 'test2': 'test2'}]

2、读取Excel文件:

from xlrd import open_workbook  #xlrd:读取excel文件的库

class ReadExcel:
    def __init__(self, path, index=0):
        #path为excel文件绝对路径,index为想要读的工作表格
        self.book = open_workbook(path)
        self.sheet = self.book.sheet_by_index(index)


    def get_excel_data(self, row, col):#获取想要读取的行为row,列为col的单元格的数据
        return self.sheet.cell(row, col).value

    def get_nrows(self):#得到总行数
        return self.sheet.nrows

    def get_ncols(self):#得到总列数
        return self.sheet.ncols

3、读取.ini配置文件:

import configparser  #configParser 模块用于操作配置文件

class ReadConfig:
    def __init__(self, path):
        #path是要读取的文件的绝对路径
        self.config_file_path = path
        self.conf = configparser.ConfigParser()
        self.conf.read(self.config_file_path)

    def get_data_file_path_data(self, dataname): #获取section为data_file_path块的key为dataname的数据value值
        return self.conf.get("data_file_path", "dataname")

4、找到json格式数据中的某个key的所有值:

from jsonpath_rw import jsonpath, parse  #提供Python中Json对象处理的jsonpath-rw

class findValue:
    def __init__(self, data, data_from):
        #data为想要找的json数据的名称,输入“male”,则寻找该json文件中所有的key为“male”的项,输入“student[*].male”则找出在student结构中的key为“male”的项
        #data_from为查找的json数据
        self.find_key = '$..%s' % (data)
        self.fromContent = data_from

    def theValue(self):  #找到符合的json数据的值
        jsonpath_expr = parse(self.find_key)
        value_content = []
        for match in jsonpath_expr.find(self.fromContent):
            value_content.append(match.value)
        return value_content

check={
    "findkey":"1",
    "truevalue":{
        "a":1,
        "findkey":"1"
    }
}

print("整个json数据中findkey的所有值是:",findValue("findkey", check).theValue())
print("整个json数据中truevalue下面的findkey的所有值是:",findValue("truevalue.findkey", check).theValue())

输出:
整个json数据中findkey的所有值是: [‘1’, ‘1’]
整个json数据中truevalue下面的findkey的所有值是: [‘1’]

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值