Python has the tempfile module for exactly this purpose. You do not need to worry about the location/deletion of the file, it works on all supported platforms.
There are three types of temporary files:
tempfile.TemporaryFile– just basic temporary file,tempfile.NamedTemporaryFile– “This function operates exactly asTemporaryFile()does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the file object.“,tempfile.SpooledTemporaryFile– “This function operates exactly asTemporaryFile()does, except that data is spooled in memory until the file size exceedsmax_size, or until the file’sfileno()method is called, at which point the contents are written to disk and operation proceeds as withTemporaryFile().“,
EDIT: The example usage you asked for could look like this:
>>> with TemporaryFile() as f:
f.write('abcdefg')
f.seek(0) # go back to the beginning of the file
print(f.read())
abcdefg