generate a temporary file that contains indicated contents and returns the filename for use. When finished the tempfile is removed.

tempfile_containing(contents[, suffix=''])

Generate a temporary file with contents specified, clean up when done.

  • contents – what should be written to the temp file
  • suffixoptional suffix of temp file, if required
Return type:

filename as string

from dhp.test import tempfile_containing

contents = 'I will not buy this record, it is scratched.'
with tempfile_containing(contents) as fname:

Use case: When testing, some functions/modules expect one or more file names to process. This phrase creates a temporary file via Python’s mkstemp, writes the contents to it and closes the file so there is no contention with the module being tested on any platform. When the with statement goes out of scope, it cleans up the temporary file.