Using NamedTemporaryDir instead of multiple NamedTemporaryFiles

Michael Hoffman 4g4trz802 at sneakemail.com
Tue Sep 9 20:49:32 CEST 2008


I am writing a library that creates temporary files and calls a series 
of external programs to process these files. Sometimes these external 
programs create files in the same directory as the input files, so to 
make sure they are all deleted, one must create them in a temporary 
directory, then delete it.

I've written a NamedTemporaryDir class which is derived somewhat from 
tempfile.NamedTemporaryFile in the standard library. Right now I am 
using NamedTemporaryFile to create individual files, but since I am 
putting them in a directory that will be deleted anyway, I'm wondering 
if I can simplify things (and not have to keep track of all fo the 
NamedTemporaryFile instances) by using tempfile.mkstemp() specifying my 
temporary directory, and relying on the directory deletion when exiting 
its with block.

Is there any reason I should keep track of each temporary files myself 
instead of deleting the whole directory?

I am using Linux, but I would also be interested in cross-platform 
considerations.

Also, the code is below. Is this worth submitting as a patch?

# NamedTemporaryFile is based somewhat on Python 2.5.2
# tempfile._TemporaryFileWrapper
#
# Original Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python
# Software Foundation; All Rights Reserved
#
# License at http://www.python.org/download/releases/2.5.2/license/

from tempfile import mkdtemp

class NamedTemporaryDir(object):
     def __init__(self, *args, **kwargs):
         self.name = mkdtemp(*args, **kwargs)
         self.close_called = False

     def __enter__(self):
         return self

     unlink = os.unlink

     def close(self):
         if not self.close_called:
             self.close_called = True
             self.unlink(self.name)

     def __del__(self):
         self.close()

     def __exit__(self, exc, value, tb):
         result = self.file.__exit__(exc, value, tb)
         self.close()
         return result



More information about the Python-list mailing list