231

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

4

6 回答 6

251

使用模块中的mkdtemp()函数tempfile

import tempfile
import shutil

dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)
于 2010-07-11T15:45:45.607 回答
177

在 Python 3 中,可以使用TemporaryDirectoryfrom模块。tempfile

例子

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()方法。但是,如果您依赖它,Pythonunittest可能会抱怨。ResourceWarning: Implicitly cleaning up <TemporaryDirectory...

于 2019-03-11T14:34:32.493 回答
40

为了扩展另一个答案,这是一个相当完整的示例,即使出现异常也可以清理 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
于 2015-10-22T18:41:47.060 回答
12

在 python 3.2 及更高版本中,stdlib https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory中有一个有用的上下文管理器

于 2016-12-22T13:03:46.053 回答
5

如果我正确地回答了您的问题,您是否还想知道临时目录中生成的文件的名称?如果是这样,试试这个:

import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
     files_in_dir = os.listdir(tmp_dir)
于 2019-12-30T15:50:31.717 回答
1

用于pathlib促进顶部的路径操作tempfile

In [1]: import tempfile
   ...: from pathlib import Path
   ...: temp_dir = Path(tempfile.TemporaryDirectory().name)
   ...: temp_dir
   ...:
Out[1]: PosixPath('/tmp/tmpqq42526o')

/可以使用pathlib的路径运算符创建新路径:

In [2]: temp_dir / "file.txt"
Out[2]: PosixPath('/tmp/tmpqq42526o/file.txt')

创建目录并写入其中的文件(其他一些文件写入方法可能会自动处理目录创建)

In [13]: temp_dir.mkdir(parents=True, exist_ok=True)
In [15]: file_name.write_text("bla")

测试文件和目录是否存在

In [19]: temp_dir.exists()
Out[19]: True

In [20]: temp_file.exists()
Out[20]: True
于 2021-11-02T11:04:41.080 回答