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
1
from pathlib import Path2
from tempfile import TemporaryDirectory3
4
with 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
| 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 |
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.