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

时间:2021-07-11 23:59:53

how to create a temporary directory and get the path / file name in python

如何在python中创建临时目录并获取路径/文件名

4 个解决方案

#1


143  

Use the mkdtemp() function from the tempfile module:

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

import tempfile
import shutil

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

#2


21  

To expand on another answer, here is a fairly complete example which can cleanup the tmpdir even on exceptions:

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

#3


8  

In python 3.2 and later, there is a useful contextmanager for this in the stdlib https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory

在python 3.2和以后的版本中,在stdlib中有一个有用的contextmanager,它是https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory

#4


4  

Use module tempfile.

tempfile使用模块。

#1


143  

Use the mkdtemp() function from the tempfile module:

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

import tempfile
import shutil

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

#2


21  

To expand on another answer, here is a fairly complete example which can cleanup the tmpdir even on exceptions:

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

#3


8  

In python 3.2 and later, there is a useful contextmanager for this in the stdlib https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory

在python 3.2和以后的版本中,在stdlib中有一个有用的contextmanager,它是https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory

#4


4  

Use module tempfile.

tempfile使用模块。