Python 2.7 中的 tempfile.TemporaryDirectory 上下文管理器 [英] tempfile.TemporaryDirectory context manager in Python 2.7

查看:160
本文介绍了Python 2.7 中的 tempfile.TemporaryDirectory 上下文管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to create a temporary directory in a context manager with Python 2.7?

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

# here the temporary diretory does not exist any more.

推荐答案

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

Another option is the "backports.tempfile" package on pypi: https://pypi.python.org/pypi/backports.tempfile

引用该项目的描述:这个包在 backports 命名空间下提供了 Python 的 tempfile 模块中新功能的 backports."

Quoting the project's description: "This package provides backports of new features in Python’s tempfile module under the backports namespace."

安装:

pip install backports.tempfile

然后在您的脚本中使用它:

Then use it in your script:

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

这篇关于Python 2.7 中的 tempfile.TemporaryDirectory 上下文管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆