summaryrefslogtreecommitdiff
path: root/src/table.py
blob: 004bd4d6a70dedaf9fbafba0db8ee7554fcdbe18 (plain)
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
import csv
from secrets import token_hex
from .exceptions import IncompatibleRowLengthError


ROW_SIZE = 3


class Table:
    def __init__(self, file_path: str):
        self.csv_params = { 'delimiter': ',', 'quotechar': '"' }
        self.csv_file = open(file_path, 'r', newline='')
        self.rows = [tuple(row) for row in csv.reader(self.csv_file, **self.csv_params)]

    def __del__(self):
        self.__write_changes()
        self.csv_file.close()

    def __write_changes(self):
        with open(f"./new_{token_hex(8)}.csv", 'w', newline='') as new_table:
            writer = csv.writer(new_table, **self.csv_params)
            for row in self.rows:
                writer.writerow(row)

    def row_at(self, index: int):
        try:
            return self.rows[index]
        except IndexError:
            return None

    def get_rows(self, n: int):
        return self.rows[:n]

    def insert(self, new_row: tuple):
        if len(new_row) != ROW_SIZE:
            raise IncompatibleRowLengthError(len(new_row))

        self.rows.append(new_row)

    def delete_at(self, to_delete: int):
        self.rows.pop(to_delete)

    def search(self, lookup: str):
        for row in self.rows:
            if lookup in row:
                return row

        return None