-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv_handler.py
82 lines (73 loc) · 2.85 KB
/
csv_handler.py
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
import csv
from typing import Any
import warnings
class CsvHandler():
"""Methods that handle CSV files.
"""
@staticmethod
def matrix_to_csv(matrix: list[list[Any]], output_path: str) -> None:
with open(output_path, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(matrix)
@staticmethod
def csv_to_matrix(input_path: str, type: str) -> list[list[Any]]:
matrix = []
with open(input_path, 'r') as f:
reader = csv.reader(f)
for row in reader:
matrix.append(row)
if type == "int":
return [[int(x) for x in row] for row in matrix]
elif type == "float":
return [[float(x) for x in row] for row in matrix]
elif type == "bool":
return [[x == 'True' for x in row] for row in matrix]
return matrix
@staticmethod
def lst_to_csv(lst: list[tuple[()]], headers: list[str], output_path: str) -> None:
with open(output_path, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(lst)
@staticmethod
def csv_to_lst(input_path: str, check_headers: list[str] = None) -> list[tuple[()]]:
lst = []
with open(input_path, 'r') as f:
reader = csv.reader(f)
headings = next(reader)
if check_headers is not None and headings != check_headers:
warnings.warn("The given headers do not correspond with the ones in the given csv file")
for row in reader: lst.append(row)
return lst
class TxtHandler():
"""Methods that handle TXT files."""
@staticmethod
def txt_to_list_of_sets(input_path: str) -> list[set[str]]:
lst = []
with open(input_path, 'r', encoding="utf-8") as f:
reader = f.read()
for line in reader.splitlines():
line_set = set()
for char in line:
line_set.add(char)
lst.append(line_set)
return lst
class StrHandler():
"""Methods that handle string parsing."""
@staticmethod
def lst_to_str(lst: list[tuple[()]], headers: list[str], column_widths: list[int]):
columns = len(headers)
if columns != len(lst[0]) or columns != len(column_widths):
raise Exception("Not same amount of headers or column widths as items per tuple")
return_string = ""
for i in range(columns):
return_string += f'%-{column_widths[i]}s' % (headers[i])
return_string += "\n"
for n in column_widths:
return_string += n*"-"
return_string += "\n"
for row in lst:
for i in range(columns):
return_string += f'%-{column_widths[i]}s' % (row[i])
return_string += "\n"
return return_string