擅长:python、mysql、java
<p>注意:您永远不能保证temp文件夹会被删除,因为用户总是会硬终止您的进程,然后它就不能运行其他任何东西。</p>
<p>也就是说,做</p>
<pre><code>temp_dir = tempfile.mkdtemp()
try:
<some code>
finally:
shutil.rmtree(temp_dir)
</code></pre>
<hr/>
<p>由于这是一个非常常见的操作,Python有一种特殊的方式来封装“do something,execute code,clean up”:a<em>context manager</em>。你可以自己写如下:</p>
<pre><code>@contextlib.contextmanager
def make_temp_directory():
temp_dir = tempfile.mkdtemp()
try:
yield temp_dir
finally:
shutil.rmtree(temp_dir)
</code></pre>
<p>把它当作</p>
<pre><code>with make_temp_directory() as temp_dir:
<some code>
</code></pre>
<p>(请注意,这使用<code>@contextlib.contextmanager</code>快捷方式创建上下文管理器。如果要按原来的方式实现一个类,则需要使用<code>__enter__</code>和<code>__exit__</code>方法创建一个自定义类;<code>__enter__</code>将创建并返回临时目录,然后<code>__exit__</code>将其删除。</p>