Read structured lines with context managers
Process line-based data safely using `with` and predictable parsing.
- Parse line records and compute totals.
In real Python scripts, with open(...) as f: is the standard way to read files safely. In this environment, we simulate file content from input, but keep the same line-processing workflow used in production.
1from io import StringIO
2
3raw = "api:2\nweb:3\nworker:1\n"
4total = 0
5with StringIO(raw) as handle:
6 for line in handle:
7 _, count = line.strip().split(":")
8 total += int(count)
9
10print(total)6
Context managers guarantee cleanup and make resource usage explicit. The loop-based record parser pattern appears in log analyzers, ETL scripts, and support tooling.
Key takeaways
Parse line records and compute totals.
Read the output to check what your program did.
Keep indentation consistent in Python blocks.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Python
Write Python in the editor and run it against sample inputs. Python runs locally in your browser using a WebAssembly runtime.
Sum service request counts
Read an integer n, then read n lines in format service:count. Print the total count.
- Three services
- Single service
Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…