Initial commit
This commit is contained in:
@ -0,0 +1 @@
|
||||
from .csvmanager import CSVManager # Imports in the package so it can be imported from the package too
|
@ -0,0 +1,16 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from loaders.formats import DataFormat
|
||||
|
||||
|
||||
class BaseDataManager(ABC):
|
||||
"""Base class for data managers."""
|
||||
|
||||
@abstractmethod
|
||||
def load(self, url: str, encoding: str = "iso8859-1"):
|
||||
"""Load data for the manager."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def export(self, url: str, fmt: DataFormat):
|
||||
"""Export data in a specific format."""
|
||||
pass
|
@ -0,0 +1,78 @@
|
||||
import csv
|
||||
|
||||
from loaders.basemanager import BaseDataManager
|
||||
from loaders.formats import DataFormat
|
||||
|
||||
|
||||
class CSVManager(BaseDataManager):
|
||||
"""
|
||||
Utility class to keep CSV data for export in other formats.
|
||||
|
||||
Attributes:
|
||||
data: Contains loaded file data as a list of lists.
|
||||
|
||||
"""
|
||||
|
||||
data: list = None
|
||||
|
||||
def __init__(self, url: str):
|
||||
"""
|
||||
Initialize the object with a URL.
|
||||
|
||||
Args:
|
||||
url: CSV URL to load from.
|
||||
|
||||
"""
|
||||
self.load(url)
|
||||
|
||||
def load(self, url: str, encoding: str = "iso8859-1"):
|
||||
"""
|
||||
Load a CSV given its file path.
|
||||
|
||||
Args:
|
||||
url: Path of the CSV file.
|
||||
encoding: Codepage name of the text file.
|
||||
|
||||
"""
|
||||
with open(url, "r", encoding=encoding) as f:
|
||||
reader = csv.reader(f, delimiter=",")
|
||||
if self.data is None:
|
||||
self.data = []
|
||||
for row in reader:
|
||||
self.data.append(row)
|
||||
|
||||
def export(self, url: str, fmt: DataFormat):
|
||||
"""Official method to export data."""
|
||||
if fmt is DataFormat.TEXT:
|
||||
self.export_text(url)
|
||||
elif fmt is DataFormat.CSV:
|
||||
self.export_csv(url)
|
||||
else:
|
||||
raise ValueError(f"{fmt}: unsupported format.")
|
||||
|
||||
def export_text(self, url: str):
|
||||
"""
|
||||
Save data as a text file.
|
||||
|
||||
Every column is save in its own line as an example.
|
||||
|
||||
Args:
|
||||
url: Output file path.
|
||||
|
||||
"""
|
||||
with open(url, "w", encoding="utf-8") as file:
|
||||
for row in self.data:
|
||||
file.write("\n".join(row))
|
||||
|
||||
def export_csv(self, url: str):
|
||||
"""
|
||||
Save data as a CSV file with semicolons.
|
||||
|
||||
Args:
|
||||
url: Output file path.
|
||||
|
||||
"""
|
||||
with open(url, "w", encoding="utf-8") as file:
|
||||
writer = csv.writer(file, delimiter=";")
|
||||
for row in self.data:
|
||||
writer.writerow(row)
|
@ -0,0 +1,7 @@
|
||||
from enum import IntEnum
|
||||
|
||||
|
||||
class DataFormat(IntEnum):
|
||||
"""Supported formats enumeration."""
|
||||
CSV = 0
|
||||
TEXT = 1
|
Reference in New Issue
Block a user