Python · Course navigation

Python files and context managers

Write and read a UTF-8 text file with automatic cleanup.

On this page
Before you start

Strings, with blocks, and standard-library imports.

  • Write and read a UTF-8 text file with automatic cleanup.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

A context manager gives a resource a well-defined lifetime. A with block closes a file even if an exception occurs while using it.

TemporaryDirectory creates an isolated location that is removed when its context exits. Explicit UTF-8 encoding keeps this text example independent of the system's default encoding.

Code example

Python
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "notes.txt"
    path.write_text("Learn\nPractice\n", encoding="utf-8")
    with path.open(encoding="utf-8") as handle:
        lines = [line.strip() for line in handle]
    print(len(lines))
    print(lines[1])
Output
2
Practice

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1from pathlib import Path
2from tempfile import TemporaryDirectory
3
4with TemporaryDirectory() as folder:
5 path = Path(folder) / "notes.txt"
6 path.write_text("Learn\nPractice\n", encoding="utf-8")
7 with path.open(encoding="utf-8") as handle:
8 lines = [line.strip() for line in handle]
9 print(len(lines))
10 print(lines[1])

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Create a temporary directory; its exact path is system-dependent.temporary directory open
—
Write two lines and close the write handle.temporary directory open
—
Read both lines and strip surrounding whitespace.lines = ['Learn', 'Practice']
—
The read handle has closed; print the line count.lines = ['Learn', 'Practice']
2
Print the second line. Leaving the outer block cleans up the directory.lines = ['Learn', 'Practice']
2
Practice

Behind the scenes

How Python processes this code

Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.

Cost and common mistakes

O(n) time and O(n) memory for n characters read into the list.

  • write_text replaces existing file contents.
  • strip removes all leading and trailing whitespace, not only the newline.

Try it yourself

Append a third line 'Review' to the text and predict the count.

Reveal answer and reasoning

The count becomes 3; lines[1] remains Practice.

Further reading