1. Home
  2. Blog
  3. Test Automation

Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp path fixtures give every test its own empty temporary folder, so code that reads and writes files can be tested without touching real data or leaving junk behind. We ran nine tests covering tmp_path, session-wide folders with tmp_path_factory, the legacy tmpdir, changing directory safely, retention of old runs and a custom basetemp.

9 min read
Pytest tmp path explained: tmp_path, tmp_path_factory and temp files

Key takeaways

  • The pytest tmp path fixture tmp_path gives each test a fresh, empty pathlib.Path folder.
  • A file written in one test did not exist in the next test’s folder, so tests cannot leak files into each other.
  • A session-scoped fixture using tmp_path_factory built a 1,000-row data file once and shared it between two tests.
  • Pytest kept only the last 3 runs’ folders: after three more runs there were still exactly 3.

Code that saves reports, exports CSV files, writes caches or reads configuration is hard to test if the test writes to real folders: it might overwrite data, depend on files left over from a previous run, or fail on another machine. The pytest tmp path fixtures solve this by giving each test its own temporary directory that pytest creates and later cleans up for you.

We used pytest 9.2.0 on Python 3.13.6; all nine tests passed. Folder locations shown are shortened, because the real ones include the user name.

Why use temporary folders in tests?

  • Safety: tests never touch real user data or the project folder.
  • Isolation: each test starts with an empty folder, so order does not matter.
  • Repeatability: no leftover files from earlier runs change the result, a common cause of flaky tests.
  • Debuggability: pytest keeps recent folders, so you can inspect what a failing test wrote.

tmp_path basics

import pathlib

def test_is_path_and_empty(tmp_path):
    assert isinstance(tmp_path, pathlib.Path)
    assert list(tmp_path.iterdir()) == []
    print("tmp name:", tmp_path.name)     # tmp name: test_is_path_and_empty0

Ask for tmp_path as a test argument, like any fixture, and you receive a pathlib.Path to a new empty directory named after the test. All the pathlib operations work on it: / to join paths, write_text, read_text, mkdir, iterdir and exists.

Each test gets its own folder

def test_unique_per_test_a(tmp_path):
    (tmp_path / "x.txt").write_text("a")
    assert len(list(tmp_path.iterdir())) == 1

def test_unique_per_test_b(tmp_path):
    assert not (tmp_path / "x.txt").exists()     # passed

The second test could not see the file the first one wrote, because each received a different folder. Parametrized tests get one folder per parameter set too, with a numbered suffix. This isolation is what lets tests run in any order or in parallel.

Testing a real function that writes files

def save_report(path, rows):
    with open(path, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["name", "total"])
        w.writerows(rows)

def test_writes_csv(tmp_path):
    out = tmp_path / "report.csv"
    save_report(out, [("Asha", 10), ("Ben", 5)])
    assert out.read_text().splitlines() == ["name,total", "Asha,10", "Ben,5"]

The pattern for any file-writing function: build a path inside tmp_path, call the function, then read the file back and assert on its contents. Design functions to accept a path argument rather than hard-coding locations, and they become easy to test this way. More file techniques are in our Python file handling guide.

Nested folders and JSON files

def test_nested_dirs(tmp_path):
    p = tmp_path / "a" / "b"
    p.mkdir(parents=True)
    (p / "c.json").write_text(json.dumps({"ok": True}))
    assert json.loads((p / "c.json").read_text()) == {"ok": True}

You can build any folder structure inside tmp_path, for example to mimic a project layout or a config directory. mkdir(parents=True) creates intermediate folders. Reading and writing JSON is covered in our Python JSON guide.

Building file fixtures and testing error paths

def load_config(path):
    with open(path) as f:
        return json.load(f)

@pytest.fixture
def config_file(tmp_path):
    p = tmp_path / "config.json"
    p.write_text(json.dumps({"retries": 3, "debug": False}))
    return p

def test_loads_config(config_file):
    assert load_config(config_file)["retries"] == 3

def test_missing_file(tmp_path):
    with pytest.raises(FileNotFoundError):
        load_config(tmp_path / "nope.json")

def test_bad_json(tmp_path):
    p = tmp_path / "bad.json"; p.write_text("{not json")
    with pytest.raises(json.JSONDecodeError):
        load_config(p)

@pytest.mark.parametrize("name", ["a", "b"])
def test_param_folders(tmp_path, name):
    print(tmp_path.name)     # test_param_folders_a_0, then test_param_folders_b_0

# 5 passed in 0.05s

Your own fixtures can depend on tmp_path to prepare files, so each test that needs a config file simply asks for config_file. Because the folder is empty and private, error paths are just as easy to test: a path that does not exist, or a file with broken content. Combine those checks with pytest.raises to prove your code fails with a clear error instead of a confusing traceback. Parametrized tests received separate folders named after each parameter, so they never share files either.

tmp_path_factory: sharing expensive files

# conftest.py
@pytest.fixture(scope="session")
def big_dataset(tmp_path_factory):
    d = tmp_path_factory.mktemp("data")
    p = d / "rows.json"
    p.write_text(json.dumps([{"id": i} for i in range(1000)]))
    print("built dataset once")
    return p

# test_files.py
def test_shared_1(big_dataset):
    assert len(json.loads(big_dataset.read_text())) == 1000
def test_shared_2(big_dataset):
    assert big_dataset.exists()

# output: "built dataset once" printed a single time

tmp_path is function-scoped, so it cannot be used by a session fixture. tmp_path_factory is session-scoped and creates new temporary folders on demand with mktemp(name). Use it for files that are slow to build, such as a generated dataset, a sample database or downloaded fixtures, and share them read-only across tests. In our run the dataset was built once for both tests. Fixture scopes are explained in our pytest fixtures guide.

Tip: treat files from a session-scoped folder as read-only. If one test modifies a shared file, other tests can pass or fail depending on order.

Code that uses relative paths

def test_chdir(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    pathlib.Path("relative.txt").write_text("hi")
    assert (tmp_path / "relative.txt").read_text() == "hi"

Some code writes to the current working directory. Combine tmp_path with monkeypatch.chdir to run the test inside the temporary folder; monkeypatch restores the original directory afterwards, even if the test fails. Never use os.chdir directly in tests, because the change would leak into every later test. See our pytest monkeypatch guide for the other environment helpers.

tmpdir: the legacy fixture

def test_legacy_tmpdir(tmpdir):
    print("tmpdir type:", type(tmpdir).__name__)    # LocalPath
    tmpdir.join("f.txt").write("x")

tmpdir and tmpdir_factory are the older versions. They return a py.path.local object (LocalPath in our run) instead of a pathlib.Path, with a different API (join, write). They still work, but the documentation recommends tmp_path and tmp_path_factory for new code. When converting, tmpdir.join("x") becomes tmp_path / "x" and .write() becomes .write_text().

Where the folders live

<system temp>/pytest-of-<user>/pytest-<N>/<test name>0/

By default, pytest creates a base folder per user inside the system temporary directory, then one numbered folder per run, then one folder per test. The folder name is derived from the test name and truncated if it is very long. On Linux and macOS a pytest-current link points to the latest run; on our Windows machine it did not exist, so look for the highest-numbered folder instead.

Retention of old runs

kept run folders: 3   ['pytest-37', 'pytest-38', 'pytest-39']
after 3 more runs, kept: 3

Pytest does not delete a test’s folder as soon as the test ends; it keeps the folders from the last three runs and removes older ones, so you can inspect output after a failure while disk usage stays bounded. Our check confirmed exactly three run folders before and after three more runs. The tmp_path_retention_count and tmp_path_retention_policy ini options change this, for example keeping folders only for failed tests; set them in your pytest ini file.

Choosing the location with –basetemp

pytest test_files.py --basetemp=./mytmp -k csv
# 1 passed;  ls mytmp  ->  test_writes_csv0

The basetemp option puts the temporary folders where you choose, without the per-user and per-run levels; our test’s folder appeared directly as mytmp/test_writes_csv0. This is handy in CI to collect test output as build artifacts. According to the pytest documentation, the basetemp directory is cleared at the start of each run, so never point it at a folder containing anything you want to keep.

Tips and common mistakes

  • Do not hard-code paths such as /tmp/test.txt; they collide between tests and break on Windows.
  • Do not use tempfile directly in tests when a fixture exists; you would have to clean up yourself.
  • Pass paths into code under test instead of patching module-level constants.
  • Open CSV files with newline="", as our example did, so line endings are consistent across platforms.
  • Remember that tmp_path is on disk: for pure in-memory logic, io.StringIO is faster and simpler.

Final thoughts

The pytest tmp path fixtures make file-handling code as easy to test as pure functions. Use tmp_path for a fresh folder per test, tmp_path_factory for expensive files shared across a session, monkeypatch.chdir for code that relies on the working directory, and basetemp when CI should keep the output. In our run every test had its own clean folder, shared data was built once, and pytest kept exactly the last three runs for debugging.

Frequently asked questions

What is tmp_path in pytest?

A built-in fixture that gives each test a new, empty temporary directory as a pathlib.Path object. Pytest creates it before the test and manages cleanup afterwards.

What is the difference between tmp_path and tmpdir?

tmp_path returns a pathlib.Path and is the recommended fixture. tmpdir is the older version that returns a py.path.local object with a different API.

How do I share a temporary file across several tests?

Create a session-scoped fixture that uses tmp_path_factory.mktemp to make a folder, writes the file once and returns its path. Treat the shared file as read-only.

Does pytest delete temporary directories?

Yes, but not immediately. By default it keeps the folders from the last three runs and removes older ones, which you can change with retention settings in the ini file.

How do I change where pytest creates temporary folders?

Pass the basetemp option with a folder path on the command line or in addopts. That folder is cleared at the start of each run, so use a dedicated location.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →