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

标签 python python-2.7 with-statement temp

有没有办法在 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

引用项目的描述:“这个包在 backports 命名空间下提供 Python 的 tempfile 模块中的新功能的反向移植。”

安装方式:

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.

关于python - Python 2.7 中的 tempfile.TemporaryDirectory 上下文管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19296146/

相关文章:

python - 将字符串格式列日期更改为 dd/mm/yyyy

python - Python 中的 while 循环终止

python - 在 tkinter 上使用 GUI 显示 pdf 页面

PHP 相当于 Javascript "with"作用域语句

Python "with"语句堆积

python - 如何将一个函数的重写一般地应用于 python 中的多个类?

java - Scala:相当于 np.digitize 对数据进行分桶

python - 如何从webapp2.Request获取数据

python - xlwt 错误消息 IOError : [Errno 13] Permission denied: 'python_spreadsheet.xls'

python - 在 Python 2.4 中处理上下文类