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.
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().
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.
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
Explain the difference between the modes "r", "w", "a" and "x".
Why should you always pass encoding="utf-8" to open, even though Python 3.15 makes UTF-8 the default?
How do you process a file too big for memory? Why does iterating a file object work?
What happens to newline characters when you read and write text files, and what is newline="" for?
Expected output
errors: 4
first: 0499 ERROR request handled
['0000 INFO request handled', '0001 INFO request handled', '0002 INFO request handled']