Python files and context managers

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

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

Explanation

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.

Explore the dry run
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

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