如何在Python中创建临时目录?

问题描述 投票:0回答:6

如何在Python中创建临时目录并获取其路径?

python temporary-files temporary-directory
6个回答
328
投票

在 Python 3 中,可以使用

TemporaryDirectory
模块中的
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()
方法。不过,如果你依赖于此,Python 的
unittest
可能会抱怨
ResourceWarning: Implicitly cleaning up <TemporaryDirectory...


283
投票

使用

mkdtemp()
模块中的
tempfile
功能:

import tempfile
import shutil

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

46
投票

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

16
投票

文档建议使用

TemporaryDirectory
上下文管理器,它会创建一个临时目录,并在退出上下文管理器时自动将其删除:

import tempfile

with tempfile.TemporaryDirectory() as tmpdirname:
    print('created temporary directory', tmpdirname)

# Outside the context manager, directory and contents have been removed.

使用

pathlib
来促进
tempfile
之上的路径操作,可以使用 pathlib 的
/
路径运算符创建新路径:

import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmpdirname:
    temp_dir = Path(tmpdirname)
    file_name = temp_dir / "test.txt"
    file_name.write_text("bla bla bla")

    print(temp_dir, temp_dir.exists())
    # /tmp/tmp81iox6s2 True

    print(file_name, "contains", file_name.open().read())
    # /tmp/tmp81iox6s2/test.txt contains bla bla bla

在上下文管理器之外,临时文件和临时目录已被破坏

print(temp_dir, temp_dir.exists())
# /tmp/tmp81iox6s2 False

print(file_name, file_name.exists())
# /tmp/tmp81iox6s2/test.txt False

13
投票

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


6
投票

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

import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
     files_in_dir = os.listdir(tmp_dir)
© www.soinside.com 2019 - 2024. All rights reserved.