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.
- The pytest tmp path fixture
tmp_pathgives each test a fresh, emptypathlib.Pathfolder. - 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_factorybuilt 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
tempfiledirectly 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.StringIOis 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
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.