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

标签 python unzip temp

我浏览了那里的示例,似乎没有找到适合的示例。

希望使用 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() 轻松解决此问题

This function securely creates a temporary directory using the same rules as mkdtemp(). The resulting object can be used as a context manager (see Examples). On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.


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

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

仅此一项就可以了

关于python - 使用 Python mkdtemp() 解压缩到临时(内存中)目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65571890/

相关文章:

R:解压缩多个文件,每个文件都在新的子目录中或重命名

visual-studio - Visual Studio 2017 安装程序在解压后无法运行

python - 使用 python 和 MySQLdb 将多个字典对象插入到 MySQL 数据库中

python - 填充文本未对齐

python - 如何在当前页面的 Pelican 站点顶部生成所有语言的链接(文章)

windows - 如何使用 DOS 命令以编程方式将存档解压缩到 Windows 上自己的目录中?

c++ - 使用 7Zlib 命令行将文件解压到目录中

r - 在 Linux 中创建临时文件夹

c++ - 获取用户临时文件夹路径 C++

python - 正则表达式:字符类中的\Z