Creating Temporary Workspaces with tempfile

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 ...

Get Intuitive Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.