Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.5 — Reading and Writing Text Files
Python · Example 4 of 4

Process a file lazily and stop early

Imagine 10 million lines instead of 2000: the loop still holds only one line at a time and stops at the first match.

open() connects your program to a file. The mode says whether you read, write or append, the encoding says how characters become bytes (always pass encoding="utf-8"), and iterating over the file reads one line at a time without loading it all.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 7 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write the numbers 1 to 5, one per line, to a file called numbers.txt. Then read the file back and print the sum of the numbers (it should print 15). Hint: each line is text, so convert it with int().

02

Write a function count_lines(path) that returns how many non-empty lines a text file has, reading it line by line (not with read()). Call it on numbers.txt. Hint: a line that is empty after strip() should not be counted.

03

Append the line done to numbers.txt (mode "a"), then print the file's last line. Hint: loop over the lines and remember the latest one.

Explain it without notes

01

Explain the difference between the modes "r", "w", "a" and "x".

02

Why should you always pass encoding="utf-8" to open, even though Python 3.15 makes UTF-8 the default?

03

How do you process a file too big for memory? Why does iterating a file object work?

04

What happens to newline characters when you read and write text files, and what is newline="" for?

Process a file lazily and stop early
Sign in to run this example in your browser.

Expected output

errors: 4
first: 0499 ERROR request handled
['0000 INFO request handled', '0001 INFO request handled', '0002 INFO request handled']