Answers:
import tempfile
import shutil
dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)
with tempfile.TemporaryDirectory() as dirpath:
,并且退出上下文管理器后,临时目录将自动清除。docs.python.org/3.4/library/…– 2016
在Python 3,TemporaryDirectory中临时文件可以使用的模块。
这直接来自示例:
import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory', tmpdirname)
# directory and contents have been removed
如果您想将目录保留更长的时间,则可以执行类似的操作(不是来自示例):
import tempfile
import shutil
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
shutil.rmtree(temp_dir.name)
正如@MatthiasRoelandts指出的那样,文档还指出“可以通过调用该cleanup()
方法来显式清理目录”。
为了扩展另一个答案,这是一个相当完整的示例,即使出现异常也可以清除tmpdir:
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)
cleanup()
@contextlib.contextmanager
def tempdir():
dirpath = tempfile.mkdtemp()
def cleanup():
shutil.rmtree(dirpath)
with cd(dirpath, cleanup):
yield dirpath
def main():
with tempdir() as dirpath:
pass # do something here
在python 3.2及更高版本中,stdlib中有一个有用的contextmanager https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory
如果我的问题正确无误,您还想知道临时目录中生成的文件名吗?如果是这样,请尝试以下操作:
import os
import tempfile
with tempfile.TemporaryDirectory() as tmp_dir:
# generate some random files in it
files_in_dir = os.listdir(tmp_dir)