本文介绍了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"包:pypi.python/pypi/backports.tempfile
Another option is the "backports.tempfile" package on pypi: pypi.python/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 上下文管理器
发布评论