How to Use the pytest tmp_path Fixture for Temporary Directories
Use pytest's built-in tmp_path fixture to create a unique temporary directory per test for clean file I/O testing.
pip install pytest
Python code
24 linesimport pytest
def test_write_and_read_file(tmp_path):
# tmp_path is a pytest fixture that provides a temporary directory
# unique to each test invocation
data_file = tmp_path / "data.txt"
data_file.write_text("hello world")
assert data_file.read_text() == "hello world"
def test_multiple_tmp_paths_are_isolated(tmp_path):
file1 = tmp_path / "file1.txt"
file2 = tmp_path / "file2.txt"
file1.write_text("content1")
file2.write_text("content2")
assert tmp_path.listdir() == [file1, file2]
assert file1.read_text() == "content1"
assert file2.read_text() == "content2"
# Run with: pytest -q test_tmp_path_example.py
Output
2 passed in 0.01s
How it works
The tmp_path fixture is a pathlib.Path object pointing to a new temporary directory that pytest creates for each test function. This guarantees isolation: each test gets a fresh directory, so files written in one test won't interfere with another. Because tmp_path is a Path, you can use methods like write_text and read_text directly, which keeps the code concise. The fixture automatically cleans up after the test session, so you don't need to manage teardown manually.
Common mistakes
- Using `tmpdir` (the older py.path.local style) instead of the more modern `tmp_path` Path object.
- Forgetting that `tmp_path` is per test, not per module — each test invocation gets a unique directory.
- Hard-coding file paths instead of using the fixture, which can lead to test pollution.
- Not using `tmp_path` as a parameter because it must be listed as a function argument.
Variations
- Use `tmp_path_factory` in fixtures to create session-scoped temporary directories.
- Call `tmp_path.mkdir()` to create subdirectories for more complex test structures.
Real-world use cases
- Testing file upload handlers by writing sample files to a temporary location and verifying content.
- Ensuring data processing logic writes correct output files without polluting the project directory.
- Snapshot testing where generated configs or reports are compared against expected files.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.