source

Python: 일시적으로 압축을 풀지 않고 zip으로 파일 열기

ittop 2023. 7. 21. 21:55
반응형

Python: 일시적으로 압축을 풀지 않고 zip으로 파일 열기

먼저 압축을 풀지 않고 zip 아카이브에서 파일을 열 수 있는 방법은 무엇입니까?

저는 pygame을 사용합니다.디스크 공간을 절약하기 위해 모든 이미지를 압축했습니다.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)

저는 이것을 지금 제 스스로 해결하려고 노력하고 있었고 이것이 미래에 이 질문을 마주치는 사람에게 유용할 것이라고 생각했습니다.

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)

  • 컨텍스트 관리자 사용의 장점 (with문)은 파일이 자동으로 올바르게 닫히는 것입니다.
  • f기본 제공되는 오픈 파일을 사용할 때 일반 파일 개체처럼 사용할 수 있습니다.

설명서 링크

이론적으로는, 네, 그것은 단지 사물을 연결하는 문제입니다.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-in-zip-without-temporarily-extracting-it

반응형