我浏览了那里的示例,似乎没有找到适合的示例。
希望使用 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/