class Table: def __init__(self, name): self.name = name self.columns = [] self.rows = [] def __str__(self): return self.name def __repr__(self): return self.name def _try_parse_int(self, value: str) -> int: try: return int(value) except ValueError: return value def load_from_csv(self, csv_file): with open(csv_file, 'r') as f: reader = f.read().splitlines() # Primeira linha contêm o nome das colunas self.columns = reader[0].split(',') reader.pop(0) for row in reader: row = row.split(',') row_list = [] for column in row: row_list.append(self._try_parse_int(column)) self.rows.append(row_list) def load_from_mysql(self, table_name, cursor): cursor.execute("SELECT * FROM " + table_name) rows = cursor.fetchall() for row in rows: row_list = [] for col in row: row_list.append(col) self.rows.append(row_list) ''' self.rows = [ ["dp001", "Customer Service"] ] ''' cursor.execute("SHOW COLUMNS FROM " + table_name) columns = cursor.fetchall() for row in columns: self.columns.append(row[0]) def save_to_csv(self): f = open("./source/" + self.name + ".csv", "w") # gravar o cabeçalho columns_line = "" for i in range(len(self.columns)): columns_line = columns_line + self.columns[i] if i < len(self.columns) - 1: columns_line = columns_line + "," f.write(columns_line + '\n') for line in range(len(self.rows)): data_line = "" for column in range(len(self.columns)): data_line = data_line + str(self.rows[line][column]) if column < len(self.columns) - 1: data_line = data_line + "," f.write(data_line + '\n') f.close()