Loading
0x70Lesson 8 of 10

Read structured lines with context managers

Process line-based data safely using `with` and predictable parsing.

12 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • 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.

main.py
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)
Output
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.

Exercise 1

Sum service request counts

+25 XP

Read an integer n, then read n lines in format service:count. Print the total count.

  • Three services
  • Single service
main.py
Loading editor…

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…