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

编程入门 行业动态 更新时间:2024-10-09 20:26:10
本文介绍了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 上下文管理器

本文发布于:2023-11-27 12:42:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638123.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上下文   管理器   Python   TemporaryDirectory   tempfile

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!