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.

import tempfile

temp = tempfile.TemporaryFile('w+')
print(temp)

#write to the file
temp.write("Hello world,")
temp.write("\nWelcome to Pynerds.")

#read from the file
temp.seek(0)
for i in temp.read():
    print(i, end = '')

temp.close()

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.

import tempfile

with tempfile.TemporaryFile('w+') as temp:

     #write to the file
     temp.write("Hello world,")
     temp.write("\nWelcome to Pynerds.")

     #read from the file
     temp.seek(0)
     for i in temp.read():
         print(i, end = '')

#the temporary file is closed.

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. 

import tempfile

with tempfile.NamedTemporaryFile() as temp:
     #get the name of the file
     print(temp.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.

import tempfile

with tempfile.NamedTemporaryFile(prefix = "project", suffix = ".py") as temp:
     #get the name of the file
     print(temp.name)

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.

import os
import tempfile

tempdir = tempfile.mkdtemp()
print(tempdir)

os.removedirs(tempdir)

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.

import os
import tempfile

tempdir = tempfile.mkdtemp(prefix = "project", suffix = "dir")
print(tempdir)

os.removedirs(tempdir)