如何删除使用tempfile.mkdtemp创建的目录? [英] How to delete a directory created with tempfile.mkdtemp?
问题描述
我有一个python程序,该程序使用tempfile.mkdtemp
在/temp
下创建临时目录.不幸的是,Python程序在使用目录后并未删除该目录.因此,现在磁盘空间不足.
I have a python program that creates temporary directories under /temp
by using tempfile.mkdtemp
. Unfortunately, the Python program did not delete the directory after using it. So now the disk space is low.
问题:
- 如何手动删除
/temp
下的临时目录?我尝试手动删除它们,但出现权限被拒绝"错误. - 在Python程序中,如何在使用它们后删除
temp
目录?
- How do I delete the temporary directories left under
/temp
manually? I tried to delete them manually but got "permission denied" error. - In the Python program, how to delete
temp
directory after using them?
推荐答案
要在Python中管理资源(如文件),最佳做法是使用with
关键字,该关键字会自动释放资源(例如,清理,清理关闭文件);这可以从Python 2.5中获得.
To manage resources (like files) in Python, best practice is to use the with
keyword, which automatically releases the resources (i.e., cleans up, like closing files); this is available from Python 2.5.
在Python 3.2中,您可以使用tempfile.TemporaryDirectory()
代替tempfile.mkdtmp()
–在with
中可用,并自动清理目录:
From Python 3.2, you can use tempfile.TemporaryDirectory()
instead of tempfile.mkdtmp()
– this is usable in with
and automatically cleans up the directory:
from tempfile import TemporaryDirectory
with TemporaryDirectory() as temp_dir:
# ... do something with temp_dir
# automatically cleaned up when context exited
如果您使用的是Python的早期版本(至少为2.5,则为with
),则可以使用 backports.tempfile ;请参阅 tempfile.TemporaryDirectory上下文管理器的 Nicholas Bishop的答案.在Python 2.7中.
If you are using an earlier version of Python (at least 2.5, so have with
), you can use backports.tempfile; see Nicholas Bishop’s answer to tempfile.TemporaryDirectory context manager in Python 2.7.
开设自己的课程(称为
上下文管理器. __enter__()
方法绑定到as
子句的目标,而__exit__()
方法在退出上下文时(即使是例外情况)被调用并执行清除.
It’s easy and instructive to roll your own class, called a
context manager. The return value of the __enter__()
method is bound to the target of the as
clause, while the __exit__()
method is called when the context is exited – even by exception – and performs cleanup.
import shutil
import tempfile
class TemporaryDirectory(object):
"""Context manager for tempfile.mkdtemp() so it's usable with "with" statement."""
def __enter__(self):
self.name = tempfile.mkdtemp()
return self.name
def __exit__(self, exc_type, exc_value, traceback):
shutil.rmtree(self.name)
您可以使用@contextlib.contextmanager
装饰器简化此过程,因此您无需手动编写上下文管理器.进入上下文时,将执行yield
之前的代码,将产生的值绑定到as
的目标,并且当退出上下文时,将执行yield
之后的代码.从根本上讲,这是一个协程,它封装了资源的获取和释放,而yield
则产生了对with
子句的套房(正文) .请注意,这里要做需要有一个try...finally
块,因为@contextlib.contextmanager
不会在yield
中捕获异常-这只是将资源管理纳入协程中.
You can simplify this with the @contextlib.contextmanager
decorator, so you don’t need to write a context manager manually. The code prior to the yield
is executed when entering the context, the yielded value is bound to the target of the as
, and the code after the yield
is executed when exiting the context. This is fundamentally a coroutine that encapsulates the resource acquisition and release, with the yield
yielding control to the suite (body) of the with
clause. Note that here you do need to have a try...finally
block, as @contextlib.contextmanager
does not catch exceptions in the yield
– this just factors the resource management into a coroutine.
from contextlib import contextmanager
import tempfile
import shutil
@contextmanager
def TemporaryDirectory():
name = tempfile.mkdtemp()
try:
yield name
finally:
shutil.rmtree(name)
正如simplelizz所指出的,如果您不介意目录已被删除(上述代码假定不会发生该目录),则可以捕获"No such file or directory"(无此类文件或目录)异常,如下所示:
As simplylizz notes, if you don’t mind the directory already being deleted (which the above code assumes does not happen), you can catch the "No such file or directory" exception as follows:
import errno
# ...
try:
shutil.rmtree(self.name)
except OSError as e:
# Reraise unless ENOENT: No such file or directory
# (ok if directory has already been deleted)
if e.errno != errno.ENOENT:
raise
您可以与 tempfile.py
;多年来,即使是这个简单的类也存在错误,并且不断发展.
You can compare with the standard implementation in tempfile.py
; even this simple class has had bugs and evolved over the years.
有关with
的背景,请参见:
- Python教程:文件对象的方法
- 使用语句上下文管理器
- PEP 343-"with"语句
- The Python Tutorial: Methods of File Objects
- With Statement Context Managers
- PEP 343 -- The "with" Statement
这篇关于如何删除使用tempfile.mkdtemp创建的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!