Testing Python code
Test isolation and temporary files
Keep tests independent of real user files.
Lesson 47 of 63
Reading: about 1 min
Lesson + practice: about 16 min
Difficulty: Intermediate
On this page5 sections
A test that writes files should work in a disposable directory. tempfile.TemporaryDirectory cleans up after the with block, while pathlib makes the path explicit.
Worked example
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
file = Path(folder) / "note.txt"
file.write_text("study", encoding="utf-8")
print(file.read_text(encoding="utf-8"))
print(file.exists())study False
Why this works
The context manager removes its temporary directory on exit. The file path object still exists as a value, but the file no longer exists.
Another case
from tempfile import TemporaryDirectory
from pathlib import Path
with TemporaryDirectory() as folder:
path = Path(folder) / "count.txt"
path.write_text("2", encoding="utf-8")
print(int(path.read_text(encoding="utf-8")) + 1)3
Practice
Write two lines to a temporary file and assert its read_text result inside the with block.
Check the practice result
Reveal answer
Write "one\ntwo\n" and compare against the same exact string, including newlines.
Try another case
Where does Path(folder) point inside the with block, and what happens to it afterwards?
Check your answer
Reveal answer
To a new temporary directory created for this run. The directory and its files are deleted when the with block ends.
Your progress
Reveal the check answer or reach the end to complete this lesson.