Use temporary directories for filesystem tests
Also published in our Blogger archive.
Direct answer
A filesystem test needs a directory it owns. TemporaryDirectory creates that directory and removes it when the with block finishes, including when an assertion raises. Constructing note.txt beneath the returned path keeps the fixture separate from files in the current working directory.
The example writes an explicit UTF-8 string and reads it with the same encoding. Comparing the entire string, including its trailing newline, catches a changed fixture or unexpected serialization rule. The printed files=1 describes the single file this snippet creates; it is not a recursive inventory of an arbitrary directory.
Keep assertions and any inspection inside the context manager. A path saved for later still names the former location after cleanup; retaining the Python object does not retain the file. Close open handles before leaving the block, especially when running tests on Windows. For evidence that must survive a failed test, copy a deliberately selected artifact to a separate output directory before cleanup.
Complete example
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
p = Path(d) / 'note.txt'
p.write_text('draft\n', encoding='utf-8')
assert p.read_text(encoding='utf-8') == 'draft\n'
result = 'files=1'
print(result)
Expected stdout (for a platform supporting the demonstrated operation):
files=1
Sources
Prepared with AI assistance. The example uses synthetic data; its stated limits apply.