How to create a temporary directory and get the path / file name in Python
如何在python中创建临时目录并获取路径/文件名
使用
1 2 3 4 5 6 | import tempfile import shutil dirpath = tempfile.mkdtemp() # ... do stuff with dirpath shutil.rmtree(dirpath) |
为了进一步讨论另一个答案,下面是一个相当完整的示例,它可以清除tmpdir,即使在异常情况下也是如此:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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中有一个有用的ContextManager用于此目的。
在python 3中,可以使用tempfile模块中的temporarydirectory。
这是直接从例子中得出的:
1 2 3 4 | import tempfile with tempfile.TemporaryDirectory() as tmpdirname: print('created temporary directory', tmpdirname) # directory and contents have been removed |
如果您想让目录保持更长一点的时间,那么可以这样做(不是从示例中):
1 2 3 4 5 6 7 | import tempfile import shutil temp_dir = tempfile.TemporaryDirectory() print(temp_dir.name) # use temp_dir, and when done: shutil.rmtree(temp_dir.name) |