Python常用方法内容系统性整合
Python自动化过程中会使用到的一些进阶方法
本文截取自API自动化(二)的数据处理部分,仅提供大致思路,获取源码可以进入链接获取
一、Excel数据处理
1、表格定位
①文件路径【file_path】,可直接赋值
②sheet名称【sheet_name】,可直接赋值
2、数据获取
①目标赋值:test_dict[“id”] = sheet.cell(i, 1).value
②加入字典:test_excel_data.append(test_dict)
class DoExcel:
def __init__(self, file_path, sheet_name):
self.file_path=file_path
self.sheet_name=sheet_name
def get_data(self):
wb = load_workbook(self.file_path)
sheet = wb[self.sheet_name]
test_excel_data = []
for i in range(2, sheet.max_row+1):
test_dict = {}
test_dict["case_id"] = sheet.cell(i, 1).value
test_dict["case_name"] = sheet.cell(i, 2).value
test_dict["method"] = sheet.cell(i, 3).value
test_dict["url"] = sheet.cell(i, 4).value
test_dict["param"] = sheet.cell(i, 5).value
test_excel_data.append(test_dict)
return test_excel_data
3、数据写入
本部分包含【初始化函数】和【数据写入】
class DoExcel:
def __init__(self, file_path, sheet_name):
self.file_path=file_path
self.sheet_name=sheet_name
def write_data(self, r, c, value):
wb = load_workbook(self.file_path)
sheet = wb[self.sheet_name]
sheet.cell(r, c).value = value
wb.save(self.file_path)
4、调式验证
可以用调试一下测试是否可以执行成功
if __name__ == "__main__":
file_path = 'G:\mine_api\test_case\api_test.xlsx'
sheet_name = 'business_collect'
test_excel_data=DoExcel(file_path, sheet_name).get_data()
print(test_excel_data)
test_excel_data=DoExcel(file_path, sheet_name).write_data() #api_test.xlsx看写入结果