0
0
PyTesttesting~5 mins

File system testing with tmp_path in PyTest

Choose your learning style9 modes available
Introduction

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.

When you want to test code that reads or writes files without affecting real data.
When you need a fresh folder or file for each test to avoid conflicts.
When you want to automatically clean up test files after tests finish.
When testing file creation, deletion, or modification in your program.
When you want to isolate file system changes to keep tests independent.
Syntax
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.

Examples
This test creates a file and checks its content.
PyTest
def test_create_file(tmp_path):
    file = tmp_path / "data.txt"
    file.write_text("Sample data")
    assert file.read_text() == "Sample data"
This test creates a folder inside the temporary path and verifies it exists.
PyTest
def test_create_folder(tmp_path):
    folder = tmp_path / "myfolder"
    folder.mkdir()
    assert folder.is_dir()
This test checks if the file was created successfully.
PyTest
def test_file_exists(tmp_path):
    file = tmp_path / "file.txt"
    file.write_text("Test")
    assert file.exists()
Sample Program

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.

PyTest
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()
OutputSuccess
Important Notes

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.

Summary

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.