How do I create a named temporary file on windows in Python? How do I create a named temporary file on windows in Python? windows windows

How do I create a named temporary file on windows in Python?


I needed something similar to this today, and ended up writing my own. I'm using atexit.register() to register a function callback that removes the file when the program exits.

Note that the coding standards for this are slightly different from the typical Python coding standards (camelCase rather than using_underscores). Adjust at will, of course.

def temporaryFilename(prefix=None, suffix='tmp', dir=None, text=False, removeOnExit=True):    """Returns a temporary filename that, like mkstemp(3), will be secure in    its creation.  The file will be closed immediately after it's created, so    you are expected to open it afterwards to do what you wish.  The file    will be removed on exit unless you pass removeOnExit=False.  (You'd think    that amongst the myriad of methods in the tempfile module, there'd be    something like this, right?  Nope.)"""    if prefix is None:        prefix = "%s_%d_" % (os.path.basename(sys.argv[0]), os.getpid())    (fileHandle, path) = tempfile.mkstemp(prefix=prefix, suffix=suffix, dir=dir, text=text)    os.close(fileHandle)    def removeFile(path):        os.remove(path)        logging.debug('temporaryFilename: rm -f %s' % path)    if removeOnExit:        atexit.register(removeFile, path)    return path

Super-basic test code:

path = temporaryFilename(suffix='.log')print pathwriteFileObject = open(path, 'w')print >> writeFileObject, 'yay!'writeFileObject.close()readFileObject = open(path, 'r')print readFileObject.readlines()readFileObject.close()


I have had exactly the same problem when I needed to save an uploaded file to the opened temporary file using the csv module. The most irritating thing was that the filename in WindowsError pointed to the temporary file, but saving the uploading file contents into the StringIO buffer and pushing the buffer data into the temporary file fixed the problem. For my needs that was enough since uploaded files always fit in memory.

The problem was only when I uploaded a file with a script through Apache's CGI, when I ran the similar script from console I could not reproduce the problem though.


If you don't care about the security what is wrong with this?

tmpfile_name = tempfile.mktemp()# do stuffos.unlink(tmpfile_name)

You might be trying to over-engineer this. If you want to make sure that this file is always removed when the program exits, you could wrap your main() execution in a try/finally. Keep it simple!

if __name__ == '__main__':    try:        tmpfile_name = tempfile.mktemp()        main()    except Whatever:        # handle uncaught exception from main()    finally:        # remove temp file before exiting        os.unlink(tmpfile_name)