如何创建临时目录并在python中获取路径/文件名
答案 0 :(得分:172)
import tempfile
import shutil
dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)
答案 1 :(得分:31)
要扩展另一个答案,这里有一个相当完整的例子,即使在例外情况下也可以清理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
答案 2 :(得分:11)
在python 3.2及更高版本中,stdlib中有一个有用的上下文管理器https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory
答案 3 :(得分:3)
在Python 3中,可以使用TemporaryDirectory模块中的tempfile。
这直接来自examples:
import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory', tmpdirname)
# directory and contents have been removed
如果您希望将目录保留更长的时间,则可以执行类似的操作(不是来自示例):
import tempfile
import shutil
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
shutil.rmtree(temp_dir.name)
答案 4 :(得分:0)
如果我正确地回答了您的问题,您还想知道临时目录中生成的文件的名称吗? 如果是这样,请尝试以下操作:
import os
import tempfile
with tempfile.TemporaryDirectory() as tmp_dir:
# generate some random files in it
files_in_dir = os.listdir(tmp_dir)