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.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 13 views 0 copies

Requires third-party packages — install first
pip install pytest

Python code

24 lines
Python 3.9+
import 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

stdout
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

  1. Use `tmp_path_factory` in fixtures to create session-scoped temporary directories.
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Testing & modern typing

Related tutorials and quizzes for this topic.