tabular-reader 0.1.0__tar.gz → 0.1.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tabular-reader
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: Read XLSX, XLS and CSV files with a uniform interface Read XLSX, XLS and CSV files with a uniform interface
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -22,10 +22,13 @@ Classifier: Programming Language :: Python :: 3.12
22
22
  Classifier: Programming Language :: Python :: 3.13
23
23
  Classifier: Programming Language :: Python :: 3.14
24
24
  Requires-Dist: openpyxl (>=3.0,<3.1)
25
+ Requires-Dist: xlrd (>=2.0,<3.0)
25
26
  Project-URL: Repository, https://github.com/arkhan/tabular-reader
26
27
  Description-Content-Type: text/plain
27
28
 
28
- * tabular_reader
29
+ #+TITLE: tabular-reader
30
+
31
+ * tabular_reader
29
32
 
30
33
  ** Description
31
34
  A module that maps information from each row in XLSX, XLS, or CSV
@@ -1,4 +1,6 @@
1
- * tabular_reader
1
+ #+TITLE: tabular-reader
2
+
3
+ * tabular_reader
2
4
 
3
5
  ** Description
4
6
  A module that maps information from each row in XLSX, XLS, or CSV
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "tabular-reader"
3
- version = "0.1.0"
3
+ version = "0.1.2"
4
4
  description = "Read XLSX, XLS and CSV files with a uniform interface Read XLSX, XLS and CSV files with a uniform interface"
5
5
  authors = ["arkhan <arkhan@riseup.net>"]
6
6
  license = "MIT"
@@ -26,6 +26,7 @@ classifiers = [
26
26
  [tool.poetry.dependencies]
27
27
  python = "^3.6"
28
28
  openpyxl = ">=3.0,<3.1"
29
+ xlrd = ">=2.0,<3.0"
29
30
 
30
31
  [tool.poetry.group.dev.dependencies]
31
32
  pytest = "^6.2"
@@ -2,5 +2,5 @@
2
2
 
3
3
  from .reader import TabularReader
4
4
 
5
- __version__ = "0.1.0"
5
+ __version__ = "0.1.2"
6
6
  __all__ = ["TabularReader"]
@@ -0,0 +1,166 @@
1
+ #!/usr/bin/env python
2
+ import csv
3
+ import io
4
+ import os
5
+ from types import SimpleNamespace
6
+
7
+
8
+ def get_file_format(filename):
9
+ if isinstance(filename, (io.BytesIO, bytes)):
10
+ return None
11
+ _, ext = os.path.splitext(filename)
12
+ return ext.lower().lstrip(".")
13
+
14
+
15
+ def read_csv(source, **kwargs):
16
+ csv_kwargs = {
17
+ k: v for k, v in kwargs.items() if k in ["delimiter", "quotechar", "encoding"]
18
+ }
19
+
20
+ if isinstance(source, io.BytesIO):
21
+ source.seek(0)
22
+ f = io.TextIOWrapper(source, encoding=csv_kwargs.pop("encoding", "utf-8-sig"))
23
+ else:
24
+ f = open(source, "r", encoding=csv_kwargs.pop("encoding", "utf-8-sig"))
25
+
26
+ try:
27
+ reader = csv.reader(f, **csv_kwargs)
28
+ total = list(reader)
29
+ finally:
30
+ if not isinstance(source, io.BytesIO):
31
+ f.close()
32
+
33
+ header = total[0] if total else []
34
+ filtered_indices = [
35
+ i for i, val in enumerate(header) if val is not None and str(val).strip() != ""
36
+ ]
37
+ return [
38
+ [row[i] if i < len(row) else None for i in filtered_indices] for row in total
39
+ ]
40
+
41
+
42
+ def read_xls(source, worksheet="", **kwargs):
43
+ import xlrd
44
+
45
+ if isinstance(source, io.BytesIO):
46
+ source.seek(0)
47
+ wb = xlrd.open_workbook(file_contents=source.read())
48
+ else:
49
+ wb = xlrd.open_workbook(source)
50
+
51
+ ws = wb.sheet_by_name(worksheet) if worksheet else wb.sheet_by_index(0)
52
+
53
+ total = [[cell.value for cell in row] for row in ws.get_rows()]
54
+ header = total[0] if total else []
55
+ filtered_indices = [
56
+ i for i, val in enumerate(header) if val is not None and str(val).strip() != ""
57
+ ]
58
+ return [
59
+ [row[i] if i < len(row) else None for i in filtered_indices] for row in total
60
+ ]
61
+
62
+
63
+ def read_xlsx(source, worksheet="", **kwargs):
64
+ from openpyxl import load_workbook
65
+
66
+ excel_kwargs = {
67
+ k: v for k, v in kwargs.items() if k not in ["delimiter", "encoding"]
68
+ }
69
+
70
+ if isinstance(source, io.BytesIO):
71
+ source.seek(0)
72
+
73
+ wb = load_workbook(source, **excel_kwargs)
74
+ ws = worksheet and wb[worksheet] or wb.active
75
+
76
+ total = [[col.value for col in row] for row in ws]
77
+ header = total[0] if total else []
78
+ filtered_indices = [
79
+ i for i, val in enumerate(header) if val is not None and str(val).strip() != ""
80
+ ]
81
+ return [
82
+ [row[i] if i < len(row) else None for i in filtered_indices] for row in total
83
+ ]
84
+
85
+
86
+ class TabularReader:
87
+ def __init__(
88
+ self,
89
+ source,
90
+ worksheet="",
91
+ fieldnames=None,
92
+ restval=None,
93
+ restkey=None,
94
+ skip_blank_lines=False,
95
+ *args,
96
+ **kwargs,
97
+ ):
98
+ file_format = get_file_format(source)
99
+
100
+ if file_format is None:
101
+ filtered_data = self._detect_and_read_bytes(source, worksheet, **kwargs)
102
+ elif file_format == "csv":
103
+ filtered_data = read_csv(source, **kwargs)
104
+ elif file_format == "xlsx":
105
+ filtered_data = read_xlsx(source, worksheet, **kwargs)
106
+ elif file_format == "xls":
107
+ filtered_data = read_xls(source, worksheet, **kwargs)
108
+ else:
109
+ raise ValueError(f"Unsupported format: {file_format}")
110
+
111
+ self.reader = iter(filtered_data)
112
+ self._fieldnames = fieldnames
113
+ self.restkey = restkey
114
+ self.restval = restval
115
+ self.skip_blank_lines = skip_blank_lines
116
+ self.line_num = 0
117
+
118
+ def _detect_and_read_bytes(self, source, worksheet, **kwargs):
119
+ errors = []
120
+
121
+ for fmt, reader_func in [
122
+ ("xlsx", read_xlsx),
123
+ ("xls", read_xls),
124
+ ("csv", read_csv),
125
+ ]:
126
+ try:
127
+ if isinstance(source, io.BytesIO):
128
+ source.seek(0)
129
+ return reader_func(source, worksheet, **kwargs)
130
+ except Exception as e:
131
+ errors.append((fmt, str(e)))
132
+ if isinstance(source, io.BytesIO):
133
+ source.seek(0)
134
+
135
+ raise ValueError(
136
+ f"Could not detect file format. Tried: {', '.join(f[0] for f in errors)}"
137
+ )
138
+
139
+ @property
140
+ def fieldnames(self):
141
+ if self._fieldnames is None:
142
+ try:
143
+ self._fieldnames = next(self.reader)
144
+ except StopIteration:
145
+ pass
146
+ self.line_num += 1
147
+ return self._fieldnames
148
+
149
+ @fieldnames.setter
150
+ def fieldnames(self, value):
151
+ self._fieldnames = value
152
+
153
+ def __iter__(self):
154
+ return self
155
+
156
+ def __next__(self):
157
+ if self.line_num == 0:
158
+ self.fieldnames
159
+ row = next(self.reader)
160
+ self.line_num += 1
161
+ while self.skip_blank_lines and all(cell is None for cell in row):
162
+ row = next(self.reader)
163
+ record = SimpleNamespace(**dict(zip(self.fieldnames, row)))
164
+ return record
165
+
166
+ next = __next__
@@ -1,103 +0,0 @@
1
- #!/usr/bin/env python
2
- import csv
3
- import os
4
- from types import SimpleNamespace
5
-
6
- from openpyxl import load_workbook
7
-
8
-
9
- def get_file_format(filename):
10
- _, ext = os.path.splitext(filename)
11
- return ext.lower().lstrip(".")
12
-
13
-
14
- def read_csv(filename, **kwargs):
15
- csv_kwargs = {
16
- k: v for k, v in kwargs.items() if k in ["delimiter", "quotechar", "encoding"]
17
- }
18
- with open(filename, "r", encoding=csv_kwargs.pop("encoding", "utf-8-sig")) as f:
19
- reader = csv.reader(f, **csv_kwargs)
20
- total = list(reader)
21
-
22
- header = total[0] if total else []
23
- filtered_indices = [
24
- i for i, val in enumerate(header) if val is not None and str(val).strip() != ""
25
- ]
26
- return [
27
- [row[i] if i < len(row) else None for i in filtered_indices] for row in total
28
- ]
29
-
30
-
31
- def read_xlsx(filename, worksheet="", **kwargs):
32
- excel_kwargs = {
33
- k: v for k, v in kwargs.items() if k not in ["delimiter", "encoding"]
34
- }
35
- wb = load_workbook(filename, **excel_kwargs)
36
- ws = worksheet and wb[worksheet] or wb.active
37
-
38
- total = [[col.value for col in row] for row in ws]
39
- header = total[0] if total else []
40
- filtered_indices = [
41
- i for i, val in enumerate(header) if val is not None and str(val).strip() != ""
42
- ]
43
- return [
44
- [row[i] if i < len(row) else None for i in filtered_indices] for row in total
45
- ]
46
-
47
-
48
- class TabularReader:
49
- def __init__(
50
- self,
51
- filename,
52
- worksheet="",
53
- fieldnames=None,
54
- restval=None,
55
- restkey=None,
56
- skip_blank_lines=False,
57
- *args,
58
- **kwargs,
59
- ):
60
- file_format = get_file_format(filename)
61
-
62
- if file_format == "csv":
63
- filtered_data = read_csv(filename, **kwargs)
64
- elif file_format in ("xlsx", "xls"):
65
- filtered_data = read_xlsx(filename, worksheet, **kwargs)
66
- else:
67
- raise ValueError(f"Unsupported format: {file_format}")
68
-
69
- self.reader = iter(filtered_data)
70
- self._fieldnames = fieldnames
71
- self.restkey = restkey
72
- self.restval = restval
73
- self.skip_blank_lines = skip_blank_lines
74
- self.line_num = 0
75
-
76
- @property
77
- def fieldnames(self):
78
- if self._fieldnames is None:
79
- try:
80
- self._fieldnames = next(self.reader)
81
- except StopIteration:
82
- pass
83
- self.line_num += 1
84
- return self._fieldnames
85
-
86
- @fieldnames.setter
87
- def fieldnames(self, value):
88
- self._fieldnames = value
89
-
90
- def __iter__(self):
91
- return self
92
-
93
- def __next__(self):
94
- if self.line_num == 0:
95
- self.fieldnames
96
- row = next(self.reader)
97
- self.line_num += 1
98
- while self.skip_blank_lines and all(cell is None for cell in row):
99
- row = next(self.reader)
100
- record = SimpleNamespace(**dict(zip(self.fieldnames, row)))
101
- return record
102
-
103
- next = __next__
File without changes