Python: Open file in zip without temporarily extracting it

后端 未结 3 943
孤独总比滥情好
孤独总比滥情好 2020-11-27 14:32

How can I open files in a zip archive without extracting them first?

I\'m using pygame. To save disk space, I have all the images zipped up. Is it possible to load a

3条回答
  •  时光取名叫无心
    2020-11-27 15:36

    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.

提交回复
热议问题