import os import openpyxl base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) test_data_path = os.path.join(base_path, "TestDatasX") def get_test_excel_list(file_dir): """獲取文件夾下所有excel文件中的sheet name ----------------這里傳一個文件路勁,要么是文件夾,要么是單個Excel :param file_dir: 文件可以是文件夾也可以是單個文件 :return: ['E:\\AutoTest_BMAPI\\TestDatasX\\search.xlsx\\search'] """ sheet_name_list = [] if file_dir.endswith("xlsx") or file_dir.endswith("xls"): """處理單個文件,確保格式一致""" sheet_name_list.append(file_dir) return [sheet_name_list] else: """處理文件夾""" for root, dir_name, data_name in os.walk(file_dir): excel_list = [] for i in data_name: if i.endswith("xlsx") or i.endswith("xls"): excel_list.append(os.path.join(root, i)) sheet_name_list.append(excel_list) return sheet_name_list def get_test_sheet_names(excel_list): sheets_name_list = [] if len(excel_list) == 1 and len(excel_list[0]) == 1: wb = openpyxl.load_workbook(excel_list[0][0]) sheet_names = wb.sheetnames for sheet_name in sheet_names: sheets_name_list.append(os.path.join(excel_list[0][0], sheet_name)) return sheets_name_list else: """獲取多Excel的sheetName""" for i in excel_list: for j in i: wb = openpyxl.load_workbook(j) sheet_names = wb.sheetnames for sheet_name in sheet_names: sheets_name_list.append(os.path.join(j, sheet_name)) return sheets_name_list def excel_path_map_sheet_name(all_excel_sheet_list): """ :param all_excel_sheet_list: 根據Excel和對應的sheetName,對list做拆分,獲取ExcelName和sheetName eg: ['E:\\pytest_selenium\\test\\TestDatasX\\search.xlsx'] :return: [('E:\\AutoTest_BMAPI\\TestDatasX\\search.xlsx', 'search')] """ case = [] for i in all_excel_sheet_list: case.append(os.path.split(i)) return case all_excel_path = r'E:\pytest_selenium\test\TestDatasX\listPage\test' print(excel_path_map_sheet_name(get_test_sheet_names(get_test_excel_list(all_excel_path))))