Temporary directories help tests create files without messing up your real folders. They clean up automatically after tests run.
Temporary directory management in PyTest
def test_example(tmp_path): # tmp_path is a pathlib.Path object for a temp directory file = tmp_path / "testfile.txt" file.write_text("hello") assert file.read_text() == "hello"
tmp_path is a built-in pytest fixture that gives a temporary directory as a pathlib.Path object.
The temporary directory is unique for each test and is deleted after the test finishes.
def test_write_file(tmp_path): file = tmp_path / "data.txt" file.write_text("data") assert file.read_text() == "data"
def test_create_subdir(tmp_path): subdir = tmp_path / "sub" subdir.mkdir() file = subdir / "info.txt" file.write_text("info") assert file.exists()
def test_temp_dir_is_empty(tmp_path): assert list(tmp_path.iterdir()) == []
This test uses pytest's tmp_path fixture to create a temporary directory. It writes a file, reads it back, and checks the content and existence. The temp directory and file are removed after the test.
import pytest def test_temp_directory(tmp_path): # Create a new file in the temp directory file_path = tmp_path / "sample.txt" file_path.write_text("pytest temp dir test") # Read the file content content = file_path.read_text() # Assert the content is correct assert content == "pytest temp dir test" # Assert the file exists assert file_path.exists()
Use tmp_path for pathlib.Path objects or tmpdir for older py.path objects.
Temporary directories are unique per test, so tests won't interfere with each other's files.
Always use these fixtures instead of hardcoding temp paths to avoid leftover files.
Temporary directories keep test files isolated and clean up automatically.
Use pytest's tmp_path fixture to get a temp directory as a pathlib.Path object.
Write and read files inside this directory to test file-related code safely.