方法一:再try之前给列表赋值,返回一个空列表
import os
import xlrd
from case_info import CaseInfo
class ExcelDataInof:
def __init__(self,file_path):
self.file_path = file_path
def read_data_in_class(self):
all_case_info = []
try:
excel_file = xlrd.open_workbook(self.file_path)
sheet = excel_file.sheet_by_index(0)
for i in range(1,sheet.nrows):
case_info = CaseInfo(sheet.cell_value(i,0),
sheet.cell_value(i,1),
sheet.cell_value(i,2),
sheet.cell_value(i,3),
sheet.cell_value(i,4),
sheet.cell_value(i,5),
sheet.cell_value(i,6),
sheet.cell_value(i,7))
all_case_info.append(case_info)
except FileNotFoundError as e:
print('文件未找到')
except IndexError as e:
print('表格sheet下标越界')
except Exception as e:
print('系统异常:'+str(e))
return all_case_info
if __name__ == '__main__':
cerrunt_path = os.path.dirname(__file__)
file_path = cerrunt_path + '/../test_case/test_c1ase.xls'
Excel_data = ExcelDataInof(file_path)
str1 = Excel_data.read_data_in_class()
print(str1[0])
方法二:try无法读取路径下,则默认去读默认文件
import os
import xlrd
from case_info import CaseInfo
class ExcelDataInof:
def __init__(self,file_path):
self.file_path = file_path
def read_data_in_class(self):
all_case_info = []
try:
excel_file = xlrd.open_workbook(self.file_path)
except FileNotFoundError as e:
cerrunt_path = os.path.dirname(__file__)
file_path = cerrunt_path + '/../test_case/test_case.xls'
excel_file = xlrd.open_workbook(file_path)
print('文件未找到')
sheet = excel_file.sheet_by_index(0)
for i in range(1,sheet.nrows):
case_info = CaseInfo(sheet.cell_value(i,0),
sheet.cell_value(i,1),
sheet.cell_value(i,2),
sheet.cell_value(i,3),
sheet.cell_value(i,4),
sheet.cell_value(i,5),
sheet.cell_value(i,6),
sheet.cell_value(i,7))
all_case_info.append(case_info)
return all_case_info
if __name__ == '__main__':
cerrunt_path = os.path.dirname(__file__)
file_path = cerrunt_path + '/../test_case/test_1c1ase.xls'
Excel_data = ExcelDataInof(file_path)
str1 = Excel_data.read_data_in_class()
print(str1[0].act_results)
方法三:第三方模块自带自定义异常
目的,就是为了二次封装的时候能封装更多自定义异常(百度-英文官方文档)
举例:
https://pypi.org/中搜索相关包(xlrd)
进入xlrd:
进入Homepage
进入xlrd的Documentation:
进入API模块查看使用方法:
from xlrd.compdoc import CompDoc
from xlrd.biffh import XLRDError