From 5e92ddf6b2e597e7e6140a1da08407b21b347982 Mon Sep 17 00:00:00 2001 From: 7000pctAUTO Date: Sun, 1 Feb 2026 19:01:14 +0000 Subject: [PATCH] Add converter modules (JSON, YAML, TOML, CSV) --- src/converters/csv_converter.py | 98 +++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 src/converters/csv_converter.py diff --git a/src/converters/csv_converter.py b/src/converters/csv_converter.py new file mode 100644 index 0000000..97b54e5 --- /dev/null +++ b/src/converters/csv_converter.py @@ -0,0 +1,98 @@ +"""CSV converter module.""" + +from typing import Any +import pandas as pd +from io import StringIO + +from .base import BaseConverter, ConversionResult + + +class CSVConverter(BaseConverter): + """Converter for CSV format.""" + + format_name = 'csv' + extensions = ('.csv',) + + def loads(self, content: str) -> Any: + """Parse CSV string to pandas DataFrame. + + Args: + content: CSV string content + + Returns: + pandas DataFrame + + Raises: + pd.errors.EmptyDataError: If content is empty + pd.errors.ParserError: If content is not valid CSV + """ + return pd.read_csv(StringIO(content)) + + def dumps(self, data: Any, indent: int = 2) -> str: + """Serialize data to CSV string. + + Args: + data: DataFrame or list of dicts to serialize + indent: Ignored for CSV (no indentation) + + Returns: + CSV string representation + """ + if isinstance(data, pd.DataFrame): + return data.to_csv(index=False) + elif isinstance(data, list) and data: + df = pd.DataFrame(data) + return df.to_csv(index=False) + else: + return "" + + def convert(self, content: str, target_converter: BaseConverter, indent: int = 2) -> ConversionResult: + """Convert content from CSV to another format. + + Args: + content: CSV source content + target_converter: Target format converter + indent: Indentation for output + + Returns: + ConversionResult with converted data or error + """ + try: + df = self.loads(content) + data = df.to_dict(orient='records') + result = target_converter.dumps(data, indent=indent) + return ConversionResult( + success=True, + data=result, + source_format=self.format_name, + target_format=target_converter.format_name + ) + except Exception as e: + return ConversionResult( + success=False, + error=str(e), + source_format=self.format_name, + target_format=target_converter.format_name + ) + + def read_file(self, filepath: str) -> str: + """Read CSV content from file. + + Args: + filepath: Path to CSV file + + Returns: + File content as string + """ + with open(filepath, 'r', encoding='utf-8') as f: + return f.read() + + def write_file(self, filepath: str, content: str) -> None: + """Write CSV content to file. + + Args: + filepath: Path to file + content: CSV content to write + """ + with open(filepath, 'w', encoding='utf-8') as f: + f.write(content)