Phi*_*ipp 186

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

import tempfile
import shutil

dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)
Run Code Online (Sandbox Code Playgroud)

  • 在python3中,你可以使用tempfile.TemporaryDirectory()作为dirpath:`,临时目录将在退出上下文管理器时自动清理.https://docs.python.org/3.4/library/tempfile.html#tempfile.TemporaryDirectory (69认同)
  • 如果在测试中使用它,请确保删除(shutil.rmtree)目录,因为它在使用后不会自动删除."完成后,mkdtemp()的用户负责删除临时目录及其内容." 请参阅:http://docs.python.org/2/library/tempfile.html#tempfile.mkdtemp (7认同)

cdu*_*001 36

为了扩展另一个答案,这里是一个相当完整的例子,即使在例外情况下也可以清理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
Run Code Online (Sandbox Code Playgroud)

  • 在 Windows 上,这是 `with tempfile.TemporaryDirectory() as tmpdir:` 的良好替代方案,因为存在[这个恼人的错误](https://bugs.python.org/issue35144),它不允许我进入临时目录 (2认同)

Pau*_*eux 19

文档建议使用TemporaryDirectory上下文管理器,它会创建一个临时目录,并在退出上下文管理器时自动删除它。使用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
Run Code Online (Sandbox Code Playgroud)

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

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

print(temp_dir, temp_dir.exists())
# /tmp/tmp81iox6s2 False
Run Code Online (Sandbox Code Playgroud)


Nag*_*gev 15

在Python 3,TemporaryDirectory临时文件可以使用的模块。

这直接来自示例

import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
     print('created temporary directory', tmpdirname)
# directory and contents have been removed
Run Code Online (Sandbox Code Playgroud)

如果您想将目录保留更长的时间,则可以执行类似的操作(不是来自示例):

import tempfile
import shutil

temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
shutil.rmtree(temp_dir.name)
Run Code Online (Sandbox Code Playgroud)

正如@MatthiasRoelandts指出的那样,文档还指出“可以通过调用该cleanup()方法来显式清理目录”。

  • Shutil.rmtree(temp_dir.name) 不是必需的。 (2认同)

And*_*ler 12

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


Sho*_*dde 6

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

import os
import tempfile

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