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


当前回答

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

import os
import tempfile

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

其他回答

Docs.python.org提供一个临时目录 实例使用 上下文管理器:

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

# Outside the context manager, 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

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

import tempfile
import shutil

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

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

import os
import tempfile

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

为了扩展另一个答案,这里有一个相当完整的示例,它可以在异常时清理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

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