2.7中的tempfile.TemporaryDirectory上下文管理器

发布于 2021-01-29 17:15:43

是否可以使用Python 2.7在上下文管理器中创建临时目录?

with tempfile.TemporaryDirectory() as temp_dir:
    # modify files in this dir

# here the temporary diretory does not exist any more.
关注者
0
被浏览
50
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    另一个选项是pypi上的“
    backports.tempfile”包:https
    ://pypi.python.org/pypi/backports.tempfile

    引用项目的描述:“此程序包在backports命名空间下的Python tempfile模块中提供了新功能的backports。”

    安装方式:

    pip install backports.tempfile
    

    然后在脚本中使用它:

    from backports import tempfile
    with tempfile.TemporaryDirectory() as temp_dir:
        # modify files in this dir
    # here the temporary directory does not exist any more.
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看