Python: 在 zip 中打开文件,不需要临时提取它

如何在不首先解压缩的情况下打开压缩文件?

我使用的是 pygame。为了节省磁盘空间,我把所有的图像都压缩了。 是否可以直接从 zip 文件加载给定的图像? 例如: pygame.image.load('zipFile/img_01')

195369 次浏览

理论上来说,是的,只需要插上插头就行了。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()

文森特 · 波维克的回答不会完全奏效;

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...

你必须改变它:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...

有关详细信息,请阅读 ZipFile文档 给你

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)

我刚才试图自己弄清楚这个问题,并且认为这对于将来遇到这个问题的任何人都可能有用。

从 Python 3.2开始,就可以使用 ZipFile作为上下文管理器:

from zipfile import ZipFile


with ZipFile('images.zip') as zf:
for file in zf.namelist():
if not file.endswith('.png'): # optional filtering by filetype
continue
with zf.open(file) as f:
image = pygame.image.load(f, namehint=file)


  • The plus side of using context managers (with statement) is that the files are automatically closed properly.
  • f可以像普通的 file object一样使用,当你使用内置的 打开()的时候。

Links to documentation