创建新的临时目录对象不会创建目录

  • 本文关键字:对象 创建目录 创建 python
  • 更新时间 :
  • 英文 :


情况 1:

创建目录 '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'

案例2:

未创建目录 '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的引用,因此该目录在创建后立即被删除。

在方法上调用.name()会导致原始类超出范围,因为它返回一个字符串,这会触发清理。若要修复此问题,请在分配类后分配名称,如第一个示例中所示。

如果您只希望创建一个目录并且只包含字符串,则可以调用较低级别的mkdtemp函数,该函数只需创建目录并返回一个字符串。

由您(或者,可能是操作系统,取决于临时目录所在的位置)来清理它。

import shutil
from tempfile import mkdtemp

temp_dir = mkdtemp()
try:
...some stuff...
finally:
shutil.rmtree(temp_dir)

最新更新