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

Posted by Chris B. on Stack Overflow See other posts from Stack Overflow or by Chris B.
Published on 2010-03-30T23:23:06Z Indexed on 2010/03/31 0:13 UTC
Read the original article Hit count: 685

Filed under:
|
|

I've got a Python program that needs to create a named temporary file which will be opened and closed a couple times over the course of the program, and should be deleted when the program exits. Unfortunately, none of the options in tempfile seem to work:

  • TemporaryFile doesn't have a visible name
  • NamedTemporaryFile creates a file-like object. I just need a filename. I've tried closing the object it returns (after setting delete = False) but I get stream errors when I try to open the file later.
  • SpooledTemporaryFile doesn't have a visible name
  • mkstemp returns both the open file object and the name; it doesn't guarantee the file is deleted when the program exits
  • mktemp returns the filename, but doesn't guarantee the file is deleted when the program exits

I've tried using mktemp1 within a context manager, like so:

def get_temp_file(suffix):
    class TempFile(object):
        def __init__(self):
            self.name = tempfile.mktemp(suffix = '.test')

        def __enter__(self):
            return self

        def __exit__(self, ex_type, ex_value, ex_tb):
            if os.path.exists(self.name):
                try:
                    os.remove(self.name)
                except:
                    print sys.exc_info()

     return TempFile()

... but that gives me a WindowsError(32, 'The process cannot access the file because it is being used by another process'). The filename is used by a process my program spawns, and even though I ensure that process finishes before I exit, it seems to have a race condition out of my control.

What's the best way of dealing with this?

1 I don't need to worry about security here; this is part of a testing module, so the most someone nefarious could do is cause our unit tests to spuriously fail. The horror!

© Stack Overflow or respective owner

Related posts about python

Related posts about Windows