如何在Python中创建临时目录并获取其路径/文件名?
发布于 2010-07-11 23:45:46
使用tempfile模块中的mkdtemp()函数:
import tempfile
import shutil
dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)发布于 2019-03-11 22:34:32
在Python3中,可以使用来自tempfile模块的TemporaryDirectory。
import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory', tmpdirname)
# directory and contents have been removed要手动控制何时删除目录,请不要使用上下文管理器,如下例所示:
import tempfile
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
temp_dir.cleanup()文档还说:
在完成上下文或销毁临时目录对象时,将从文件系统中删除新创建的临时目录及其所有内容。
例如,在程序结束时,如果目录没有被删除,Python将清理它,例如通过上下文管理器或cleanup()方法。但是,如果您依赖于此,Python的unittest可能会抱怨ResourceWarning: Implicitly cleaning up <TemporaryDirectory...。
发布于 2015-10-23 02:41:47
为了扩展另一个答案,这里有一个相当完整的示例,它可以清理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 herehttps://stackoverflow.com/questions/3223604
复制相似问题