Using NamedTemporaryDir instead of multiple NamedTemporaryFiles

Gabriel Genellina gagsl-py2 at
Tue Sep 9 22:04:04 CEST 2008

En Tue, 09 Sep 2008 15:49:32 -0300, Michael Hoffman  
<4g4trz802 at> escribió:

> 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.

Looks fine...

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

Windows won't let you remove a non-empty directory.

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


Gabriel Genellina

More information about the Python-list mailing list