Working with text and files
Project: save a study log
Save a study log as JSON and create a readable text summary.
Lesson 33 of 63
Reading: about 2 min
Lesson + practice: about 18 min
Difficulty: Beginner
On this page4 sections
Create save_study_log.py in a practice folder. The program stores a list of session dictionaries in JSON and writes a text summary. Running it again replaces its two output files.
For file practice, download the Python practice files v1.0.0 bundle. The examples write their own files, so the samples stay unchanged. Work on a copy if you edit a sample.
Build the files
import json
from pathlib import Path
sessions = [
{"subject": "Python", "minutes": 25},
{"subject": "SQL", "minutes": 40},
]
json_path = Path("study_log.json")
summary_path = Path("study_summary.txt")
json_path.write_text(json.dumps(sessions, indent=2), encoding="utf-8")
loaded = json.loads(json_path.read_text(encoding="utf-8"))
total = sum(session["minutes"] for session in loaded)
summary_path.write_text(f"Sessions: {len(loaded)}\nTotal: {total} min\n", encoding="utf-8")
print(summary_path.read_text(encoding="utf-8").strip())Sessions: 2 Total: 65 min
Why this works
The program writes a list of sessions to JSON, loads that file back, and computes a total from the loaded data. It writes a separate human-readable summary. This round trip checks that the stored data can be parsed, but it does not validate every possible malformed or unexpected file; Chapter 7 handles those failures.
Check and extend
Open both files and confirm they contain two sessions and a 65-minute total. Add a 15-minute Python session, rerun, and expect three sessions and 80 minutes.
Why load the JSON before calculating the total?
Reveal answer
It verifies that the saved JSON can be read back and used as Python data.
Try another case
Why are study_log.json and study_summary.txt separate files?
Check your answer
Reveal answer
JSON keeps structured session data that Python can load; the text file presents a short summary for a person to read.
Your progress
Reveal the check answer or reach the end to complete this lesson.