1.读取yaml配置文件
from os.path import exists
from yaml import safe_load_all, safe_load
class File(object):
def __init__(self, file_path: str):
if not exists(file_path):
raise FileNotFoundError
self._file_path = file_path
self._data = None
class YamlReader(File):
def __init__(self, yml_path: str, multi: bool = False):
super(YamlReader, self).__init__(yml_path)
self._multi = multi
@property
def data(self):
if not self._data:
with open(self._file_path, 'rb') as fp:
if self._multi:
self._data = list(safe_load_all(fp))
else:
self._data = safe_load(fp)
return self._data
1.读取excel配置文件
from os.path import exists
from xlrd import open_workbook
class File(object):
def __init__(self, file_path: str):
if not exists(file_path):
raise FileNotFoundError
self._file_path = file_path
self._data = None
class ExcelReader(File):
def __init__(self, excel_path: str, sheet: [str, int], excel_title: bool = False):
super(ExcelReader, self).__init__(excel_path)
self._sheet = sheet
self._excel_title = excel_title
self._data = []
@property
def data(self):
if not self._data:
work_book = open_workbook(self._file_path)
if not isinstance(self._sheet, (str, int)):
raise TypeError("excel 表格不,{}不存在".format(self._sheet))
if isinstance(self._sheet, int):
s = work_book.sheet_by_index(self._sheet)
else:
s = work_book.sheet_by_name(self._sheet)
if self._excel_title:
title = s.row_values(0)
for col in range(1, s.nrows):
self._data.append(dict(zip(title, s.row_values(col))))
else:
for col in range(1, s.nrows):
self._data.append(s.row_values(col))
return self._data