python create data loader factory with interface to load multiple data files abc.csv, bcd.csv. and proces all in one class
Assistant
To create a flexible and reusable data loader factory in Python that can load and process multiple CSV files (like abc.csv, bcd.csv) through a unified interface inside one class, you can follow an approach like this:
Goals:
Define a single class that acts as a factory and loader.
Allow registering multiple filenames to load.
Load and process all files in one place.
Provide a unified interface for data access or further processing.
Example Implementation
python
import pandas as pd
from typing import List, Dict
class DataLoaderFactory:
def __init__(self, file_paths: List[str] = None):
# Store file paths
self.file_paths = file_paths or []
# Dictionary to hold loaded dataframes
self.dataframes: Dict[str, pd.DataFrame] = {}
def register_file(self, file_path: str):
"""Add a new file to the loader."""
self.file_paths.append(file_path)
def load_all(self):
"""Load all files into memory."""
for file_path in self.file_paths:
# Extract filename without extension to use as key
key = file_path.split('/')[-1].split('.')[0]
try:
df = pd.read_csv(file_path)
self.dataframes[key] = df
print(f"Loaded {file_path} successfully.")
except Exception as e:
print(f"Failed to load {file_path}: {e}")
def process_all(self):
"""Example processing method that processes all dataframes."""
for key, df in self.dataframes.items():
# Example processing: add a column indicating the source file
df['source'] = key
# You can add more processing here
self.dataframes[key] = df
def get_combined_data(self) -> pd.DataFrame:
"""Combine all loaded dataframes into a single dataframe."""
if not self.dataframes:
print("No data loaded.")
return pd.DataFrame()
combined_df = pd.concat(self.dataframes.values(), ignore_index=True)
return combined_df
# Usage example:
if __name__ == "__main__":
loader = DataLoaderFactory(['abc.csv', 'bcd.csv'])
loader.load_all()
loader.process_all()
combined_df = loader.get_combined_data()
print(combined_df.head())
Explanation:
file_paths: Holds all CSV files to load.
dataframes: A dictionary mapping filename keys to their loaded pandas DataFrames.
register_file(): Add new files after initialization if needed.
load_all(): Loads all CSV files and keeps DataFrames in the dictionary.
process_all(): An example placeholder for any processing you want to do on each loaded DataFrame.
get_combined_data(): Returns a single DataFrame that concatenates all loaded data, useful for downstream processing.
You can extend process_all() for more specific data cleaning, filtering, transformations, etc. This design centralizes loading/processing and supports multiple datasets with a clean interface.