Creating a Temporary Directory
So far, we’ve created permanent entries in the file system. For various reasons like parking data temporarily it can be necessary to just have a temporary directory. The
tempfile module contains methods that handle such cases in a safe and consistent way.
Listing 5 shows an example that uses the
TemporaryDirectory() method in combination with the
with statement. After the
with statement the temporary directory does not exist anymore because both the directory, and its contents have been entirely removed.
import tempfile # create a temporary directory with tempfile.TemporaryDirectory() as directory: print('The created temporary directory is %s' % directory) # directory and its contents have been removed by this point