2010-07-11 77 views

回答

136

使用来自tempfile模块mkdtemp()功能:

import tempfile 
import shutil 

dirpath = tempfile.mkdtemp() 
# ... do stuff with dirpath 
shutil.rmtree(dirpath) 
+7

如果你在测试中使用它,一定要删除(shutil.rmtree)目录,因为它在使用后不会自动删除。 “mkdtemp()的用户负责在完成时删除临时目录及其内容。”请参阅:http://docs.python.org/2/library/tempfile.html#tempfile.mkdtemp – 2013-11-12 11:42:39

+1

这必须是被接受的答案! – gregoltsov 2014-10-02 13:42:02

+23

在python3中,你可以使用tempfile.TemporaryDirectory()作为dirpath:',临时目录会在退出上下文管理器时自动清除。 https://docs.python.org/3.4/library/tempfile.html#tempfile.TemporaryDirectory – Symmetric 2016-02-04 23:11:51

19

为了扩大在另一个答案,这里是一个相当完整的例子可以清理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 
+0

请参阅http://stackoverflow.com/a/24176022/263998 – cdunn2001 2015-10-22 18:44:52

+0

比接受的答案更有用! – Timo 2016-01-28 14:31:30

相关问题