我如何在Python中创建一个临时目录并获取其路径/文件名?
当前回答
如果我正确地回答了您的问题,您还想知道在临时目录中生成的文件的名称吗? 如果是,试试这个:
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
使用tempfile模块中的mkdtemp()函数:
import tempfile
import shutil
dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)
在python 3.2及以后版本中,在stdlib https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory中有一个有用的上下文管理器
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
如果我正确地回答了您的问题,您还想知道在临时目录中生成的文件的名称吗? 如果是,试试这个:
import os
import tempfile
with tempfile.TemporaryDirectory() as tmp_dir:
# generate some random files in it
files_in_dir = os.listdir(tmp_dir)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录