<p>处理临时文件和目录的一个好方法是通过上下文管理器。这就是如何使用<a href="http://docs.python.org/2.7/library/tempfile.html#tempfile.TemporaryFile" rel="noreferrer">tempfile.TemporaryFile</a>或<a href="http://docs.python.org/2.7/library/tempfile.html#tempfile.NamedTemporaryFile" rel="noreferrer">tempfile.NamedTemporaryFile</a>——一旦退出<code>with</code>语句(通过普通的exit、return、exception或其他方式),文件/目录及其内容将从文件系统中删除。</p>
<p>对于Python 3.2+,它内置为<a href="http://docs.python.org/3.2/library/tempfile.html#tempfile.TemporaryDirectory" rel="noreferrer">tempfile.TemporaryDirectory</a>:</p>
<pre><code>import tempfile
with tempfile.TemporaryDirectory() as temp_dir:
... do stuff ...
</code></pre>
<p>对于早期的Python版本,您可以轻松地创建自己的上下文管理器来执行完全相同的操作。这里与@katrialex answer的不同之处在于将args传递给<code>mkdtemp()</code>和try/finally块,以确保在引发异常时清除目录。</p>
<pre><code>import contextlib
import shutil
@contextlib.contextmanager
def temporary_directory(*args, **kwargs):
d = tempfile.mkdtemp(*args, **kwargs)
try:
yield d
finally:
shutil.rmtree(d)
# use it
with temporary_directory() as temp_dir:
... do stuff ...
</code></pre>
<p>注意,如果进程被硬终止(例如<code>kill -9</code>),那么目录将不会被清理。</p>