Skip to main content
 首页 » 编程设计

python之创建新的 TemporaryDirectory 对象不会创建目录

2024年09月07日8thcjp

案例一:

目录“C:\Users\jim\AppData\Local\Temp\tmp9lf9xalc”已创建。

In [1]: 
from tempfile import TemporaryDirectory 
temp_dir = TemporaryDirectory() 
temp_dir.name 
 
Out [1]: 
'C:\\Users\\jim\\AppData\\Local\\Temp\\tmp9lf9xalc' 

案例二:

目录“C:\Users\jim\AppData\Local\Temp\tmpm861vgbn”未创建。

In [2]: 
from tempfile import TemporaryDirectory 
temp_dir = TemporaryDirectory().name 
temp_dir 
 
Out [2]: 
'C:\\Users\\jim\\AppData\\Local\\Temp\\tmpm861vgbn' 

我不明白为什么在案例 2 中没有创建目录。

TemporaryDirectory源码如下。它位于 ..\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) 

请您参考如下方法:

正如文档字符串所说,您应该使用 with:

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

然后它会知道您何时完成目录并为您删除它。作为备份,它还会在 TemporaryDirectory 对象被销毁 时进行清理,发出 ResourceWarning,因为这种行为及其时间无法在 Python 中得到保证实现。

在你的第二种情况下,这个备份会立即发生(对于 CPython),因为你没有保留对 TemporaryDirectory 的引用,所以目录一创建就被删除。