python excel和yaml檔案的讀取封裝
阿新 • • 發佈:2021-01-13
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)
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="請輸入密碼"]','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 檔案讀取與封裝的資料請關注我們其它相關文章!