Python: Open file in zip without temporarily extracting it

后端 未结 3 944
孤独总比滥情好
孤独总比滥情好 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:12

    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:

    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()
    

提交回复
热议问题