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.
Python code
34 linesfrom 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
{'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
- Add parameters to `save` for custom JSON options like `sort_keys` or a default value
- 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
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.