ChatGPT解决这个技术问题 Extra ChatGPT

如何创建临时目录并获取其路径/文件名?

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


S
Samuel Rossille

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

import tempfile
import shutil

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

如果您在测试中使用它,请务必删除 (shutil.rmtree) 目录,因为它不会在使用后自动删除。 “使用 mkdtemp() 的用户负责删除临时目录及其内容。”请参阅:docs.python.org/2/library/tempfile.html#tempfile.mkdtemp
在python3中,你可以做with tempfile.TemporaryDirectory() as dirpath:,临时目录会在退出上下文管理器时自动清理。 docs.python.org/3.4/library/…
N
Nagev

在 Python 3 中,可以使用 tempfile 模块中的 TemporaryDirectory

examples

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...


shutil.rmtree(temp_dir.name) 不是必需的。
“如果没有明确删除,Python 将清理目录”——我认为这仅适用于使用上下文管理器样式 (with ...) 的情况。
如果我使用 sleep(5) 而不是 temp_dir.cleanup() 运行第二个示例(无上下文管理器),我可以在程序完成之前 ls 临时目录,并且在完成之后相同的目录消失了。不过,最好使用上下文管理器或 cleanup() 方法。
c
cdunn2001

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

Windows 上 with tempfile.TemporaryDirectory() as tmpdir: 的好替代品,因为有 this annoying bug 不允许我进入临时目录
A
André Keller

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


S
Shoval Sadde

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

import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
     files_in_dir = os.listdir(tmp_dir)

P
Paul Rougieux

Docs.python.org TemporaryDirectory example 使用上下文管理器

import tempfile
# create a temporary directory using the context manager
with tempfile.TemporaryDirectory() as tmpdirname:
    print('created temporary directory', tmpdirname)
# directory and contents have been removed

使用 pathlib 来促进在 tempfile 之上的路径操作使得使用 pathlib 的 / path 运算符创建新路径成为可能:

import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmpdirname:
    temp_dir = Path(tmpdirname)
    print(temp_dir, temp_dir.exists())
    file_name = temp_dir / "test.txt"
    file_name.write_text("bla bla bla")
    print(file_name, "contains", file_name.open().read())

# /tmp/tmp81iox6s2 True
# /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

@Flimm 而 TemporaryFile 的文档提到“它会在关闭后立即被销毁(包括当对象被垃圾收集时的隐式关闭)”。 TemporaryDirectory 的情况并非如此,我们可以期待更长的持续时间,至少可以执行诸如临时文件解包之类的操作,这些文件太大而无法放入内存。文件内容是临时的,会立即转移到其他地方。
@Flimm 你是对的,最好使用上下文管理器。我更新了我的答案。