python读取excel文件代码封装_python excel和yaml文件的读取封装

excel

import os

import xlrd

path = lambda p: os.path.abspath(

os.path.join(os.path.dirname(__file__), p)

)

class exceldata:

def __init__(self, file, sheet="sheet1", title=true):

# 判断文件存在不存在

if os.path.isfile(path(file)):

self.file = path(file)

self.sheet = sheet

self.title = title

self.data = list()

self.workbook = xlrd.open_workbook(self.file)

else:

raise filenotfounderror("文件不存在")

@property

def get_data(self):

"""获取表格数据"""

if not self.data:

# 判断表单名称

if type(self.sheet) not in [int, str]:

raise exception("表单名称类型错误")

else:

if type(self.sheet) == int:

book = self.workbook.sheet_by_index(self.sheet)

else:

book = self.workbook.sheet_by_name(self.sheet)

# 判断表格是否有表头,有则输出列表嵌套字典形式数据,否则输入列表嵌套列表形式数据

if self.title:

title = book.row_values(0)

for i in range(1, book.nrows):

self.data.append(dict(zip(title, book.row_values(i)))) # 可参考字典章节

else:

for i in range(book.nrows):

self.data.append(book.row_values(i))

return self.data

@property

def get_sheets(self):

"""获取所有表单,这个在后续会用到"""

book = self.workbook.sheets()

return book

调用操作

infos = exceldata("htmls/测试用例.xlsx", "登入页面", true).get_data

print(infos)

sheets = exceldata("htmls/测试用例.xlsx").get_sheets

print(sheets)

0b436b707a6376ba275a14617de9f81c.png

yaml

import os

import yaml

from yamlinclude import yamlincludeconstructor

yamlincludeconstructor.add_to_loader_class(loader_class=yaml.fullloader) # 用于yaml文件嵌套

path = lambda p: os.path.abspath(os.path.join(

os.path.dirname(__file__), p

))

class yamldata:

def __init__(self, file):

if os.path.isfile(path(file)):

self.file = path(file)

else:

raise filenotfounderror("文件不存在")

@property # 设置属性,调用data方法时可通过调用属性,不需要带括号

def data(self):

with open(file=self.file, mode="rb") as f:

infos = yaml.load(f, loader=yaml.fullloader)

# infos = yaml.load(f)

return infos

调用操作

infos = yamldata("htmls/loginsucess.yaml").data

print(infos)

"d:\program files\python\python37-32\python.exe" d:/demo/yamldata.py

{'id': 'login_001', 'module': '登入页面', 'title': '登入时账号为空', 'message': '已打开链接', 'testcase': [{'element_info': 'css->[placeholder="请输入账号"]', 'operate_type': 'send_keys', 'keys': 'ssss', 'info': '点击账号输入框,输入账号'}, {'element_info': 'css->[placeholder="请输入密码"]', 'operate_type': 'send_keys', 'keys': 'xxx', 'info': '点击密码输入框,输入密码'}, {'element_info': 'div->"登 录"', 'operate_type': 'click', 'info': '点击登入菜单'}, {'operate_type': 'is_sleep', 'keys': 3, 'info': '等待进入'}], 'check': none}

process finished with exit code 0

以上就是python excel和yaml文件的读取与封装的详细内容,更多关于python 文件读取与封装的资料请关注萬仟网其它相关文章!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值