使用 Python mkdtemp() 解压缩到临时内存中目录?

问题描述

我已经查看了那里的示例,但似乎没有找到适合的示例。

希望使用 Python mkdtemp() 将内存中的文件解压缩到临时目录。

这样的东西感觉很直观,但我找不到正确的语法:

import zipfile
import tempfile


zf = zipfile.Zipfile('incoming.zip')

with tempfile.mkdtemp() as tempdir:
    zf.extractall(tempdir)

# do stuff on extracted files

但这会导致:

AttributeError                            Traceback (most recent call last)
<ipython-input-5-af39c866a2ba> in <module>
      1 zip_file = zipfile.ZipFile('incoming.zip')
      2 
----> 3 with tempfile.mkdtemp() as tempdir:
      4     zip_file.extractall(tempdir)

AttributeError: __enter__

解决方法

我已经在评论中提到了为什么您编写的代码不起作用。 .mkdtemp() 仅以字符串形式返回路径,但您真正想要的是上下文管理器。

您可以使用正确的函数 .TemporaryDirectory()

轻松解决此问题

该函数使用与 mkdtemp() 相同的规则安全地创建一个临时目录。生成的对象可用作上下文管理器(参见示例)。完成上下文或临时目录对象的销毁后,新创建的临时目录及其所有内容将从文件系统中删除。


zf = zipfile.ZipFile('incoming.zip')

with tempfile.TemporaryDirectory() as tempdir:
    zf.extractall(tempdir)

这个就行了

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...