How to Load and Inspect Data Files in Python

A beginner-friendly DataLoader dataclass that loads JSON or text files and provides methods to preview and inspect the data.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 15 views 0 copies

Python code

50 lines
Python 3.9+
from dataclasses import dataclass, field
from pathlib import Path
import json
from typing import Any, Dict, List


@dataclass
class DataLoader:
    """Simple helper to load and inspect data files for beginners."""
    path: Path
    data: Any = field(init=False, default=None)

    def __post_init__(self) -> None:
        self.path = Path(self.path)
        self.load()

    def load(self) -> None:
        """Load JSON or plain text file based on extension."""
        if self.path.suffix == ".json":
            with self.path.open("r", encoding="utf-8") as f:
                self.data = json.load(f)
        else:
            self.data = self.path.read_text(encoding="utf-8")

    def head(self, n: int = 5) -> List[Any]:
        """Return first n records for quick inspection."""
        if isinstance(self.data, list):
            return self.data[:n]
        return list(self.data.items())[:n] if isinstance(self.data, dict) else self.data[:n]

    def info(self) -> Dict[str, Any]:
        """Basic metadata about loaded data."""
        if isinstance(self.data, list):
            return {"type": "list", "length": len(self.data)}
        if isinstance(self.data, dict):
            return {"type": "dict", "keys": list(self.data.keys())}
        return {"type": "text", "characters": len(self.data)}


if __name__ == "__main__":
    # Create a demo JSON file to work with
    sample = Path("sample_people.json")
    sample.write_text('[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]', encoding="utf-8")

    loader = DataLoader(sample)
    print(loader.info())
    print(loader.head(1))

    # Cleanup demo file
    sample.unlink()

Output

stdout
{'type': 'list', 'length': 2}
[{'name': 'Alice', 'age': 30}]

How it works

The @dataclass decorator automatically generates __init__, __repr__, and other dunder methods, reducing boilerplate. field(init=False) ensures data is not required as a constructor argument and is set during __post_init__. The load method uses the file extension to choose between json.load for structured data and read_text for raw text. isinstance checks allow head and info to behave differently for lists, dicts, and strings, giving beginners a safe way to explore unknown data shapes.

Common mistakes

  • Forgetting to convert a string path to `Path` before using `.suffix`
  • Using `json.loads` instead of `json.load` when reading from a file object
  • Not specifying `encoding='utf-8'` which can cause encoding errors on some platforms

Variations

  1. Use `pathlib.Path.read_text` with `json.loads` for a one-liner JSON load.
  2. Add support for CSV with the `csv` module when a `.csv` suffix is detected.

Real-world use cases

  • Quickly inspect a downloaded dataset before writing ETL code in a data pipeline.
  • Previewing configuration or state files during local debugging in a script.
  • Providing a lightweight abstraction for file loading in a teaching or onboarding tool.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.