forked from smarthaut/Daemon_AutoFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_reader.py
More file actions
86 lines (74 loc) · 2.56 KB
/
file_reader.py
File metadata and controls
86 lines (74 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/11 10:45
# @Author : huanghe
# @Site :
# @File : file_reader.py
# @Software: PyCharm
""""
文件读取,YamlReader读取yaml文件,ExcelReader读取excel文件。后续可添加其他类
"""
import yaml
import os
from xlrd import open_workbook
import configparser as cparser
class YamlReader:
def __init__(self,yaml):
if os.path.exists(yaml):
self.yaml = yaml
else:
raise FileNotFoundError('配置文件不存在')
self._data = None
@property
def data(self):
if not self._data:
with open(self.yaml,'rb')as f:
self._data = list(yaml.safe_load_all(f))
return self._data
class SheetTypeError(Exception):
pass
class ExcelReader:
"""
读取excel文件中的内容。返回list。
如:
excel中内容为:
| A | B | C |
| A1 | B1 | C1 |
| A2 | B2 | C2 |
如果 print(ExcelReader(excel, title_line=True).data),输出结果:
[{A: A1, B: B1, C:C1}, {A:A2, B:B2, C:C2}]
如果 print(ExcelReader(excel, title_line=False).data),输出结果:
[[A,B,C], [A1,B1,C1], [A2,B2,C2]]
可以指定sheet,通过index或者name:
ExcelReader(excel, sheet=2)
ExcelReader(excel, sheet='BaiDuTest')
可用于做接口自动化
"""
def __init__(self, excel, sheet=0, title_line=True):
if os.path.exists(excel):
self.excel = excel
else:
raise FileNotFoundError('文件不存在!')
self.sheet = sheet
self.title_line = title_line
self._data = list()
@property
def data(self):
if not self._data:
workbook = open_workbook(self.excel)
if type(self.sheet) not in [int, str]:
raise SheetTypeError('Please pass in <type int> or <type str>, not {0}'.format(type(self.sheet)))
elif type(self.sheet) == int:
s = workbook.sheet_by_index(self.sheet)
else:
s = workbook.sheet_by_name(self.sheet)
if self.title_line:
title = s.row_values(0) # 首行为title
for col in range(1, s.nrows):
# 依次遍历其余行,与首行组成dict,拼到self._data中
self._data.append(dict(zip(title, s.row_values(col))))
else:
for col in range(0, s.nrows):
# 遍历所有行,拼到self._data中
self._data.append(s.row_values(col))
return self._data