We use tmp_path to create temporary files and folders during tests. This keeps tests safe and clean without changing real files on your computer.
File system testing with tmp_path in PyTest
def test_example(tmp_path): file = tmp_path / "testfile.txt" file.write_text("Hello") content = file.read_text() assert content == "Hello"
tmp_path is a built-in pytest fixture that provides a temporary directory as a pathlib.Path object.
You can create files or folders inside tmp_path safely during tests.
def test_create_file(tmp_path): file = tmp_path / "data.txt" file.write_text("Sample data") assert file.read_text() == "Sample data"
def test_create_folder(tmp_path): folder = tmp_path / "myfolder" folder.mkdir() assert folder.is_dir()
def test_file_exists(tmp_path): file = tmp_path / "file.txt" file.write_text("Test") assert file.exists()
This test creates a file named hello.txt in a temporary folder, writes text to it, reads it back, and checks the content and existence of the file.
import pytest def test_write_and_read(tmp_path): # Create a new file in the temporary directory file = tmp_path / "hello.txt" file.write_text("Hello, pytest!") # Read the content back content = file.read_text() # Check if the content is correct assert content == "Hello, pytest!" # Check the file exists assert file.exists()
Each test gets a fresh temporary directory, so files from one test won't affect another.
Temporary files and folders are deleted automatically after the test finishes.
Use tmp_path when you want to work with real file paths and tmp_path_factory for more control over temporary directories.
tmp_path helps test file operations safely without touching real files.
It provides a temporary folder unique to each test.
Files and folders created inside tmp_path are cleaned up automatically.