How to Load and Inspect CSV Data with a Dataclass Helper in Python
This code defines a DataHelper dataclass that reads a CSV file into a list of dictionaries and prints basic dataset information.
Python code
38 linesfrom pathlib import Path
from dataclasses import dataclass
from typing import Any
@dataclass
class DataHelper:
"""Simple helper for loading and inspecting CSV data."""
filepath: Path
def load_csv(self, *, delimiter: str = ",") -> list[dict[str, Any]]:
"""Read CSV into a list of dictionaries."""
import csv
with self.filepath.open(newline="") as f:
reader = csv.DictReader(f, delimiter=delimiter)
return [dict(row) for row in reader]
def describe(self, data: list[dict[str, Any]]) -> None:
"""Print basic information about the dataset."""
if not data:
print("Dataset is empty.")
return
columns = list(data[0].keys())
print(f"Rows: {len(data)}")
print(f"Columns: {columns}")
print("Sample row:", data[0])
if __name__ == "__main__":
import tempfile
sample = Path("sample_data.csv")
sample.write_text("name,age,city\nAlice,30,Berlin\nBob,25,Paris\n", encoding="utf-8")
helper = DataHelper(sample)
dataset = helper.load_csv()
helper.describe(dataset)
sample.unlink(missing_ok=True)
Output
Rows: 2
Columns: ['name', 'age', 'city']
Sample row: {'name': 'Alice', 'age': '30', 'city': 'Berlin'}
How it works
The DataHelper class uses @dataclass to automatically generate an initializer for the filepath field. The load_csv method uses csv.DictReader to parse each row into a dictionary, using the header row as keys. The describe method prints the row count, column names, and a sample row for quick inspection. Using Path from pathlib ensures cross-platform file handling. The if __name__ == '__main__' block creates a sample CSV, demonstrates the helper, then cleans up the file.
Common mistakes
- Forgetting to convert rows from `csv.DictReader` to `dict`, which may cause issues with `OrderedDict` in older Python versions.
- Not closing the file explicitly (though the `with` context manager handles it here).
- Assuming all rows have the same columns; `data[0].keys()` only reflects the first row's headers.
Variations
- Use `pandas.read_csv()` for more advanced data analysis and transformation.
- Add type validation or data cleaning inside `load_csv` to handle missing values.
Real-world use cases
- Quickly prototyping data exploration scripts where you need a lightweight CSV reader without pulling in pandas.
- Building a reusable utility in a data pipeline to load configuration or reference data from CSV files.
- Teaching beginners how to wrap file I/O and parsing in a clean, object-oriented interface.
Sponsored
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.