Python:以zip格式打开文件而不临时解压缩
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19371860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Open file in zip without temporarily extracting it
提问by user2880847
How can I open files in a zip archive without extracting them first?
如何在不先解压的情况下打开 zip 存档中的文件?
I'm using pygame. To save disk space, I have all the images zipped up.
Is it possible to load a given image directly from the zip file?
For example:
pygame.image.load('zipFile/img_01')
我正在使用 pygame。为了节省磁盘空间,我把所有的图片都压缩了。是否可以直接从 zip 文件加载给定的图像?例如:
pygame.image.load('zipFile/img_01')
采纳答案by Jellema
Vincent Povirk's answer won't work completely;
Vincent Povirk 的答案不会完全奏效;
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...
You have to change it in:
您必须将其更改为:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...
For details read the ZipFile
docs here.
有关详细信息,请阅读此处的ZipFile
文档。
回答by Vincent Povirk
In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:
理论上,是的,这只是插入东西的问题。Zipfile 可以为您提供一个类似文件的对象,用于 zip 存档中的文件,而 image.load 将接受类似文件的对象。所以这样的事情应该有效:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
image = pygame.image.load(imgfile, 'img_01.png')
finally:
imgfile.close()
回答by Brandon
import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')
# read bytes from archive
img_data = archive.read('img_01.png')
# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)
img = pygame.image.load(bytes_io)
I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.
我刚才试图为自己解决这个问题,并认为这对将来遇到这个问题的任何人都可能有用。