如何在Python中创建临时目录并获取路径/文件名


Answers:


210

使用模块中的mkdtemp()功能tempfile

import tempfile
import shutil

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

7
如果在测试中使用此目录,请确保删除(shutil.rmtree)目录,因为使用后该目录不会自动删除。“ mkdtemp()的用户负责在完成后删除临时目录及其内容。” 参见:docs.python.org/2/library/tempfile.html#tempfile.mkdtemp
Niels Bom

97
在python3中,您可以执行with tempfile.TemporaryDirectory() as dirpath:,并且退出上下文管理器后,临时目录将自动清除。docs.python.org/3.4/library/…– 2016
对称

41

在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()方法来显式清理目录”。


2
shutil.rmtree(temp_dir.name)是不必要的。
sidcha '19

37

为了扩展另一个答案,这是一个相当完整的示例,即使出现异常也可以清除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


3

如果我的问题正确无误,您还想知道临时目录中生成的文件名吗?如果是这样,请尝试以下操作:

import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
     files_in_dir = os.listdir(tmp_dir)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.