This implements a Python ContextManager for working with temporary files. Open a temporary file with mode as in open(), e.g. ‘wb’. The mkstemp_args keyword arguments are handed to the tempfile.mkstemp() function: tempfile.mkstemp([suffix=’‘[, prefix=’tmp’[, dir=None[, text=False]]]]).
Yields a tuple, (filename, openfile), for use in a with statement, where filename is a string naming the file and openfile is the open file object. The openfile will be closed when the context is exited. Caller is responsible for deleting filename when it’s no longer needed.
>>> text = 'foobar'
>>> with opentemp('wb', suffix='_.tmp', prefix='onyx_opentemp_test_') as (filename, outfile):
... outfile.write(text)
>>> filename
'/.../onyx_opentemp_test_..._.tmp'
>>> os.stat(filename).st_size == len(text)
True
>>> with open(filename, 'rb') as infile:
... infile.read() == text
True
>>> os.remove(filename)