developer tip

python : 임시 압축 해제없이 zip에서 파일 열기

copycodes 2020. 12. 30. 08:18
반응형

python : 임시 압축 해제없이 zip에서 파일 열기


압축을 풀지 않고 zip 아카이브에서 파일을 열려면 어떻게해야합니까?

파이 게임을 사용하고 있습니다. 디스크 공간을 절약하기 위해 모든 이미지를 압축했습니다. zip 파일에서 직접 주어진 이미지를로드 할 수 있습니까? 예를 들면 :pygame.image.load('zipFile/img_01')


Vincent Povirk의 대답은 완전히 작동하지 않습니다.

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)

나는 지금 바로 이것을 알아 내려고 노력하고 있었고 이것이 미래 에이 질문을 접하는 모든 사람들에게 유용 할 것이라고 생각했습니다.


이론적으로는 연결 만하면됩니다. 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()

참조 URL : https://stackoverflow.com/questions/19371860/python-open-file-from-zip-without-temporary-extracting-it

반응형