Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new TemporaryDirectory object doesn't create the directory

Tags:

python

Case 1:

The directory 'C:\Users\jim\AppData\Local\Temp\tmp9lf9xalc' is created.

In [1]:
from tempfile import TemporaryDirectory
temp_dir = TemporaryDirectory()
temp_dir.name

Out [1]:
'C:\\Users\\jim\\AppData\\Local\\Temp\\tmp9lf9xalc'

Case 2:

The directory 'C:\Users\jim\AppData\Local\Temp\tmpm861vgbn' is NOT created.

In [2]:
from tempfile import TemporaryDirectory
temp_dir = TemporaryDirectory().name
temp_dir

Out [2]:
'C:\\Users\\jim\\AppData\\Local\\Temp\\tmpm861vgbn'

I don't understand why in Case 2 the directory is not created.

The source code of TemporaryDirectory is as follows. It's located at ..\Anaconda3\envs\my_env\Lib\tempfile.py

class TemporaryDirectory(object):
    """Create and return a temporary directory.  This has the same
    behavior as mkdtemp but can be used as a context manager.  For
    example:

        with TemporaryDirectory() as tmpdir:
            ...

    Upon exiting the context, the directory and everything contained
    in it are removed.
    """

    def __init__(self, suffix=None, prefix=None, dir=None):
        self.name = mkdtemp(suffix, prefix, dir)
        self._finalizer = _weakref.finalize(
            self, self._cleanup, self.name,
            warn_message="Implicitly cleaning up {!r}".format(self))

    @classmethod
    def _cleanup(cls, name, warn_message):
        _shutil.rmtree(name)
        _warnings.warn(warn_message, ResourceWarning)

    def __repr__(self):
        return "<{} {!r}>".format(self.__class__.__name__, self.name)

    def __enter__(self):
        return self.name

    def __exit__(self, exc, value, tb):
        self.cleanup()

    def cleanup(self):
        if self._finalizer.detach():
            _shutil.rmtree(self.name)
like image 940
GoCurry Avatar asked Oct 21 '25 05:10

GoCurry


1 Answers

As the doc string says, you’re supposed to use with:

with TemporaryDirectory() as tmpdir:
  loc=tmpdir.name
  # ...

Then it knows when you’re done with the directory and removes it for you. As a backup, it also cleans up when the TemporaryDirectory object is destroyed, issuing a ResourceWarning because that behavior and its timing cannot be guaranteed across Python implementations.

This backup happens immediately (for CPython) in your second case, since you kept no reference to the TemporaryDirectory, so the directory is removed as soon as it is created.

like image 185
Davis Herring Avatar answered Oct 23 '25 19:10

Davis Herring



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!