──────────────────────────────────────

1. Files That Do Work · Write and Read a Field Note

Write text with UTF-8 encoding and read it back using a context manager.

Lesson files · lessons/files-and-formats/text-files

Before you start
- Read a line with input() and print a labelled message.
- Follow indentation to tell which statements belong in a block.

By the end
- Write a note as UTF-8 and read it back with its original spelling.
- Point to where the file closes and where the temporary folder is removed.

Where you can use it
Save a handover note to a text file and read it back before passing it to the next volunteer.

So far, input() has read text and print() has displayed it. A file gives you a place to store text and read it later in the same run. Path comes from pathlib, a module that ships with Python. Path(folder) / "note.txt" joins the folder and filename.

Follow the two indented with blocks in the example. The outer block makes a temporary folder. The inner block opens the file in write mode and closes it when that block ends. The print line can then read the note while the folder still exists.

Write mode "w" can replace existing contents. The starter creates and cleans up a practice folder for you. UTF-8 preserves characters such as é. Each Studio run starts with its own fresh files.

Predict
When does the inner file close?
- When Python leaves the inner with block.
- Only when the interpreter exits.

Worked example (example.py)

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    note = Path(folder) / "note.txt"
    with note.open("w", encoding="utf-8") as file:
        file.write("Sky clear.")
    print(note.read_text(encoding="utf-8"))


Example result
Sky clear.

Write the line from Program input to note.txt in the temporary folder. After the inner with block closes the file, read the note back and print it with the prefix “Note: ”. Try the accented-text case.

Starter program (starter.py)

from pathlib import Path
from tempfile import TemporaryDirectory

message = input()
with TemporaryDirectory() as folder:
    note = Path(folder) / "note.txt"
    with note.open("w", encoding="utf-8") as file:
        file.write("Draft note")
    print(note.read_text(encoding="utf-8"))


Starter input
Tshepo spotted a springbok.

Hint
The starter puts the input in message. Write that value, then use note.read_text(encoding="utf-8") to read what was saved.

Case 1. Try the sample
Input
Tshepo spotted a springbok.
Expected output
Note: Tshepo spotted a springbok.

Case 2. UTF-8 text
Input
Café opened
Expected output
Note: Café opened

Stretch
Write two notes using a newline, then print the number of lines read.

Reflect
Why is a temporary directory a good place to practise writing files?

Check your prediction
When Python leaves the inner with block. The context manager closes the file after the block, so it can be read with the new contents.
