Opening, Reading, and Writing
Scenario: A script must count log errors and save a report.
New words, in plain English
- File handle - the Python object connected to an open file
- Mode - whether a file is opened for reading, writing, or appending
- Encoding - the rule mapping text to bytes
Use with open(path, mode, encoding="utf-8") as handle so closure is automatic. Iterate for large files. w replaces content; a appends; binary modes add b.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
with open("server.log", encoding="utf-8") as source:
errors = [line for line in source if "ERROR" in line]
with open("report.txt", "w", encoding="utf-8") as out:
out.writelines(errors)
Tip: Be explicit about encoding for portable text files.
Goal: Practice this idea in the py-read-file challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.