How to Use tmpdir Fixture in pytest for Temporary Directories
In pytest, the
tmpdir fixture provides a temporary directory unique to each test function. You can use it by adding tmpdir as a parameter to your test, then create files or folders inside it safely without affecting your real file system.Syntax
The tmpdir fixture is used by declaring it as a parameter in your test function. It provides a py.path.local object representing a temporary directory.
tmpdir.mkdir("subfolder"): creates a subdirectory.tmpdir.join("file.txt"): creates a file path inside the temp directory..write("text"): writes text to a file.
python
def test_example(tmpdir): sub = tmpdir.mkdir("subfolder") file = sub.join("testfile.txt") file.write("hello") assert file.read() == "hello"
Example
This example shows how to use tmpdir to create a temporary file, write data, and verify its contents. The temporary directory and files are removed automatically after the test finishes.
python
def test_write_and_read(tmpdir): temp_file = tmpdir.join("sample.txt") temp_file.write("pytest tmpdir example") content = temp_file.read() assert content == "pytest tmpdir example"
Output
============================= test session starts ==============================
collected 1 item
test_tmpdir_example.py . [100%]
============================== 1 passed in 0.03s ===============================
Common Pitfalls
Common mistakes when using tmpdir include:
- Not using
tmpdiras a test function parameter, so pytest won't inject it. - Trying to use
tmpdiroutside test functions or fixtures. - Confusing
tmpdirwithtmp_path(the newer pathlib-based fixture).
Always use tmpdir inside test functions and avoid hardcoding paths.
python
import os def test_wrong_usage(): # Wrong: tmpdir not passed as parameter temp_dir = tmpdir # NameError: tmpdir is not defined # Correct usage: def test_right_usage(tmpdir): file = tmpdir.join("file.txt") file.write("data") assert file.read() == "data"
Quick Reference
| Action | Method | Description |
|---|---|---|
| Create subdirectory | tmpdir.mkdir("name") | Creates a new folder inside the temp directory |
| Create file path | tmpdir.join("filename") | Returns a file path object inside temp directory |
| Write to file | file.write("text") | Writes text content to the file |
| Read from file | file.read() | Reads text content from the file |
| Get path string | str(tmpdir) | Returns the string path of the temp directory |
Key Takeaways
Use
tmpdir by adding it as a parameter to your test function to get a temporary directory.tmpdir allows safe creation of files and folders that are deleted after tests run.Always write and read files using
tmpdir.join() and its methods to avoid path errors.Do not use
tmpdir outside test functions or without declaring it as a parameter.Consider
tmp_path fixture for pathlib-based temporary directories in newer pytest versions.