Python files and context managers
Write and read a UTF-8 text file with automatic cleanup.
On this page
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
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])2 Practice
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
from pathlib import Pathfrom 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])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
| Step / line | What happens | State after step | Output 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.