How to Build a Simple Data Helper Class in Python

A beginner-friendly DataHelper class that safely saves and loads JSON files with automatic directory creation, perfect for production-style file handling.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 12 views 0 copies

Python code

34 lines
Python 3.9+
from pathlib import Path
import json


class DataHelper:
    """Simple production-style helper for loading and saving JSON data."""

    def __init__(self, data_dir="data"):
        self.data_dir = Path(data_dir)
        self.data_dir.mkdir(exist_ok=True)

    def save(self, filename, data):
        filepath = self.data_dir / filename
        with filepath.open("w") as f:
            json.dump(data, f, indent=2)

    def load(self, filename):
        filepath = self.data_dir / filename
        if not filepath.exists():
            return None
        with filepath.open() as f:
            return json.load(f)


if __name__ == "__main__":
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        helper = DataHelper(tmp)
        helper.save("user.json", {"name": "Alice", "age": 30})
        user = helper.load("user.json")
        print(user)
        print("Loaded from:", helper.data_dir)
        print("Missing file returns:", helper.load("nonexistent.json"))

Output

stdout
{'name': 'Alice', 'age': 30}
Loaded from: /tmp/tmpxyz123
Missing file returns: None

How it works

The DataHelper class wraps JSON file operations into reusable methods. It uses pathlib.Path for cross-platform file paths and mkdir(exist_ok=True) to create the directory only if needed. The save method writes JSON with indentation for readability, while load returns None for missing files instead of raising errors. This pattern keeps file I/O centralized, making it easy to swap storage backends or add validation later. The if __name__ == '__main__' guard allows the file to be imported without running the demo.

Common mistakes

  • Using `json.dump` with a string path instead of an open file object
  • Forgetting to create the directory, causing FileNotFoundError on first save
  • Assuming the file exists and not handling the None return from load()

Variations

  1. Add parameters to `save` for custom JSON options like `sort_keys` or a default value
  2. Use `json.loads` with `Path.read_text()` if you prefer concise one-liners

Real-world use cases

  • Persisting user preferences or session data in desktop applications.
  • Storing processed data from batch jobs for later inspection or debugging.
  • Managing simple configuration state for microservices without a database.

Sponsored

Run this sample

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

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.