Week 6 · Lesson 3 · 55 minutes

Save a report without losing the log

Choose read write and append modes for different jobs.

Planned lesson. Follow your teacher’s teaching order.

Source workbook pages: 38.

Resources

Vocabulary

Vocabulary
write mode: Create a file or replace its existing contents; append mode: Add text at the end of a file; newline: A character that starts a new line
55-minute lesson sequence
  1. 0–5 · Answer the retrieval alone. Compare one reason.
  2. 5–15 · Teacher models the example. Students predict each next step.
  3. 15–40 · Build, trace and test the main tasks. Work alone first; compare after a checkpoint.
  4. 40–50 · Check results. Explain a test and repair one error. Use the extension only if ready.
  5. 50–55 · Complete the exit alone. Save the evidence for the next lesson.

Try before notes

Which readings are at least 25 in [18, 22, 27, 25]?

Build the idea

Read, write and append modes have different effects. r reads an existing file. w creates a file or truncates an existing file immediately on opening. a adds output at the end. Choose the mode from the purpose, not from convenience.

Protect the source log by writing a report to a different filename. Convert numbers to strings when building text output. Include newline characters deliberately so report fields do not run together.

Read the saved file back and compare its text with the expected report. Printing correct numbers to the screen does not prove that the output file is correct. Work in a fresh practice folder.

input.log --r→ values --analysis→ report.txt (w)
                              └→ history.txt (a)

See the method

Use a new file named mode_demo.txt, not the input file. First write A and a newline. Then append B and a newline. The file contains two lines, A and B. Running a new w block with C replaces both old lines with C. File writing uses strings.

with open("mode_demo.txt", "w", encoding="utf-8") as target:
    target.write("A\n")
with open("mode_demo.txt", "a", encoding="utf-8") as target:
    target.write("B\n")

Predict then reveal

A new demo.txt is written with "red\n", then appended with "blue\n". What is the file text? A later w block writes "green\n". What remains?

Reveal reasoning

After append: "red\nblue\n", two lines. Opening in w truncates the old content; after the later write, only "green\n" remains.

A file contains "end" with no final newline. Append "next\n". Will next start on a new line?

Reveal reasoning

No. The exact text becomes "endnext\n". Append does not automatically insert a newline. The program must include separators where its format requires them.

Work one step together

Read the first task. Each learner predicts the first step privately. Compare the method, then complete one intermediate row or one code iteration together. Do not display a finished workbook answer.

Practice

  1. Build write_summary(filename, values, threshold). Write two lines: count=4 and high=2 for the current readings and threshold 25. Use summary.txt, not readings.txt. Read the summary back to check it.

Your turn

Complete the remaining steps of task 1 alone, then the next tasks. Predict before running code. Save your own evidence before comparing.

Practice

  1. Build write_summary(filename, values, threshold). Write two lines: count=4 and high=2 for the current readings and threshold 25. Use summary.txt, not readings.txt. Read the summary back to check it.
  2. Append the line checked 4 readings to checks.txt. Run the append code twice. Predict the contents. Why is a right for this history but w right for a fresh summary?
  3. A program uses open("readings.txt", "w") before it reads the input. What is the risk? Give two ways to prevent the mistake.

Check and explain

Opening in w can destroy existing content before any write call happens.

Point to the first step, row, condition or requirement that supports your answer. If results differ, find the first different state and repair one cause.

Show what you know

You must add one new event and keep all old events. Which mode?

HL challenge when ready

What happens if the file already ends with no newline and you append "25\n"?

Week 6 homework

Show working. Keep code and output. Stop at 25 minutes and mark where you reached.

  1. Without running code first, predict the report for a new file containing 24, 25, 26, a blank line and 19. Use limit 25. Then, if a computer is available, test and compare. Otherwise trace the function on paper.
  2. A check history already has three lines. A program appends one line each run. It runs twice. How many lines are there? What would change if it used w each time?
  3. Write one test that catches > used instead of >= at limit 25. State the input and expected answer.

Source workbook pages: 41.

Weekly homework (Word)

Python practice · two short prompts

Spend about 3 minutes on each during practice time. Predict, run, change one thing, then explain. These prompts do not add homework.

A starter is runnable code to explore or complete. If the playground restores your saved code, the linked starter is selected in Example: use Load example when ready. Download your work before confirming replacement.

Prompt 1

Write a report to a separate temporary file and read it back.

Import Path from pathlib (standard library).

Hint and starter code

Use a report filename distinct from the input log. Browser files are temporary; download important work.

# Use a report filename distinct from the input log.
from pathlib import Path

report = Path("practice_report.txt")
report.write_text("count: 3\n", encoding="utf-8")
print(report.read_text(encoding="utf-8"))
Open this starter in Python playground →
Prompt 2

Format a summary from a list; guard against an empty list before calculating a mean.

No imports needed.

Hint and starter code

A mean is the sum divided by the count; dividing by zero is invalid.

# A mean is the sum divided by the count; dividing by zero is invalid.
readings = [24, 27, 29]
if readings:
    print("count", len(readings))
    print("mean", sum(readings) / len(readings))
else:
    print("no valid readings")
Open this starter in Python playground →