Create a Data Helper Class in Python
A reusable DataHelper class that saves and loads JSON and CSV files from a configurable base directory, with automatic header detection for CSV.
Python code
50 linesimport json
import csv
from pathlib import Path
class DataHelper:
def __init__(self, base_path="."):
self.base_path = Path(base_path)
self.base_path.mkdir(exist_ok=True)
def save_json(self, data, filename):
path = self.base_path / filename
with open(path, "w") as f:
json.dump(data, f, indent=2)
print(f"Saved JSON to {path}")
def save_csv(self, rows, filename, headers=None):
path = self.base_path / filename
if headers is None:
headers = list(rows[0].keys()) if rows else []
with open(path, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=headers)
writer.writeheader()
writer.writerows(rows)
print(f"Saved CSV to {path}")
def load_json(self, filename):
path = self.base_path / filename
with open(path) as f:
return json.load(f)
def load_csv(self, filename):
path = self.base_path / filename
with open(path) as f:
reader = csv.DictReader(f)
return [dict(row) for row in reader]
if __name__ == "__main__":
helper = DataHelper("data_examples")
sample_data = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25}
]
helper.save_json(sample_data, "people.json")
helper.save_csv(sample_data, "people.csv")
loaded_json = helper.load_json("people.json")
loaded_csv = helper.load_csv("people.csv")
print(f"JSON loaded: {loaded_json[0]['name']}")
print(f"CSV loaded: {loaded_csv[1]['age']}")
Output
Saved JSON to data_examples/people.json
Saved CSV to data_examples/people.csv
JSON loaded: Alice
CSV loaded: 25
How it works
The DataHelper class centralizes file I/O operations into simple, reusable methods, following the Facade design pattern by hiding file path management and serialization complexities. Path.mkdir(exist_ok=True) ensures the base directory exists without raising errors on repeated calls. The csv.DictWriter with fieldnames=headers writes a header row automatically, and csv.DictReader returns rows as dictionaries for easy access. Using newline='' in open prevents CSV writer adding extra blank lines on Windows. By wrapping these operations, beginners get a stable interface for common data file tasks.
Common mistakes
- Forgetting the `newline=''` parameter when writing CSV files, which can cause blank lines on Windows
- Assuming the CSV headers always match the data keys without specifying them explicitly
- Using a relative path that changes depending on where the script is run from
- Loading a JSON file that doesn't exist without catching the `FileNotFoundError`
Variations
- Add methods like `delete_file` or `get_full_path` for more control
- Use `json.dumps` with `sort_keys=True` to sort keys for consistent output
Real-world use cases
- Creating a local data cache for a desktop app to persist user preferences and session state.
- Building a test fixture generator that writes sample datasets for unit tests.
- Implementing a simple ETL utility that exports database query results to CSV for reporting.
Sponsored
More from System design patterns
- Build a BFF (Backend for Frontend) Mock Aggregator in Python medium
- Builder pattern for mocking complex objects in Python easy
- Circuit Breaker Pattern in Python: Closed, Open, and Half-Open States medium
- Domain Driven Design Aggregate Root Example in Python medium
- Facade Pattern in Python with Mock Simplification medium
- How to Aggregate Mock API Routes by Method in Python easy
Keep learning
Related tutorials and quizzes for this topic.