Creating Temporary Workspaces with tempfile
Intuitive Python — by David Muller (17 / 41)
👈 Using the collections Module for Concise Code | TOC | Calling Other Programs with subprocess 👉
The tempfile module allows you to create files and directories that are automatically deleted when you are done with them. As you’ll see in this section, the tempfile module can be particularly useful when testing code that writes to the file system by allowing you to create new and isolated files and directories that are automatically cleaned up for you as the test ends.
tempfile has a number of convenience functions and classes, but you’ll learn about two of the most useful in this section: NamedTemporaryFile and TemporaryDirectory.
Creating Temporary Files with NamedTemporaryFile
NamedTemporaryFile allows you to create a new file on the file system that is automatically deleted when you are done with it. Like other file operations, one of the most convenient ways to use NamedTemporaryFile is by using it in a with context manager (which ensures that file resources are properly cleaned up when you are finished):[48]
import os
from tempfile import NamedTemporaryFile
with NamedTemporaryFile() as tmp_f:
print(tmp_f.name, os.path.exists(tmp_f.name))
print(tmp_f.name, os.path.exists(tmp_f.name))