首页 > 其他 > 详细

读取yaml和excel配置文件

时间:2021-05-25 17:09:31      阅读:16      评论:0      收藏:0      [点我收藏+]

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

  

 

读取yaml和excel配置文件

原文:https://www.cnblogs.com/yoyo1216/p/14809077.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!