1

I have a zip file called "main.zip". Inside that, I have another zip called "meta" which does not have the ".zip" extension. I want to open the "meta" zip file which contains lots of text files. But when I try to open the "meta" zip file, I get an error saying zipfile.BadZipfile: File is not a zip file. Below is my code:

zf = zipfile.ZipFile(inputZipFile, 'r')
print(zf.namelist())    # [u'meta']
zf2 = zipfile.ZipFile(zf.open('meta')) # throws error

I can't extract and open "meta" because I want to do this entirely in memory without writing to the disk.

My ultimate goal is to modify one of the text files and output a new zip.

Parth Bhoiwala
  • 1,282
  • 3
  • 19
  • 44

1 Answers1

3

If you're intent on doing this in memory, you need to create a file-like object to call zipfile.ZipFile on. Although ZipFile.open says that it does this, in practice I'm getting the same error you are.

What I've gotten to work is to read the binary with ZipFile.read and toss it into a io.BytesIO stream.

import io

with zipfile.ZipFile("main.zip") as zf:
    f2 = io.BytesIO(zf.read("meta"))
    with zipfile.ZipFile(f2) as zf2:
        # this is inside the inner zip file
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • 1
    That worked like magic. Seriously, I have been trying something similar since hours with `StringIO` but it didn't work. `BytesIO` did the job. Thank you – Parth Bhoiwala May 10 '17 at 18:20
  • Hi @ParthBhoiwala ! i have the same situation as yours. Just that I just need to extract the files out of meta and thats it. I am not able to extract the files in meta. Can you help? – rohit nair Jun 16 '20 at 07:06