tempfile
is one of the various modules in the Python Standard Library. It is used for creating temporary files and directories in a secure manner. All the temporary files and directories created by tempfile
are removed when the program exits.
The module provides several functions for representing and manipulating temporary files and directories, some of them are as shown in the following table.
function | description |
---|---|
TemporaryFile() |
Creates, opens and returns a temporary unnamed file. |
NamedTemporaryFile() |
Creates a temporary file whose name is the concatenation of a given prefix and a random string |
TemporaryDirectory() |
Creates a temporary directory. |
mkdtemp() |
Creates a unique temporary directory whose name can be reliably determined. |
Temporary Files
Temporary files are useful when a program needs to store temporary data, cache information, etc. The files are not accessible to other programs, so they provide a secure method of accessing, storing and transferring data.
The TemporaryFile
function creates temporary files that are automatically deleted once they are closed, whether by the close()
method or as a context manager in the with
statement. The files are accessible within the program as normal file objects. They can be opened, written to, and read from just like any other file.
By default, the file is created with mode ’w+b’
so binary data can be written to and read from from it.
In the above example we created a temporary file and specified "w+" as the mode, this allows us to write and read regular text from the file. After writing to the file, the file cursor moves to the end of the file, so we had to call the seek()
method to "rewind" the cursor back to the beginning of the file.
We can alternatively, use the file object as a context manager in the with statement. This alleviates the need to manually close the file using the close()
method.
Named temporary files
Temporary files created using the TemporaryFile()
class do not have a meaningful name, if we want a named file we can use the NamedTemporaryFile()
function. The function creates a file with a randomly generated name.
You can specify a prefix
and a suffix
that will be used at the start and at the end of the generated name, respectively.
Temporary Directories
When multiple temporary files are needed, it maybe more convenient to create a temporary directory to store them. The mkdtemp()
function creates a unique, temporary directory on the system and returns its name.
Since you cannot "close" a directory like a file, we have to explicitly remove the directory when we are done using it. We used the os.removedirs()
function to remove the directory.
We can also specify prefix
and suffix
parameters when calling the function.