简体   繁体   中英

How to Store a ZipFile Inside a ZipFile using the zipfile library in python

I would like to store a ZipFile inside a ZipFile, while i use the.write method to write the ZipFile object i end up getting an error "expected str, bytes or os.PathLike object, not ZipFile"

>>> from io import StringIO
>>> import zipfile
>>> child_zip = zipfile.ZipFile(StringIO(), 'w', compression=zipfile.ZIP_DEFLATED, allowZip64=True)
>>> parent_zip = zipfile.ZipFile(zipfile.ZipFile, 'w', compression=zipfile.ZIP_DEFLATED, allowZip64=True)
>>> parent_zip.write("test.zip",child_zip)

First:

The ZipFile.write method expects a filename as its first argument, and it will then open and read data from that file, writing it to the archive. You need to use the writestr method to write raw data into parent_zip .

Second:

You're creating parent_zip like this:

parent_zip = zipfile.ZipFile(zipfile.ZipFile, 'w',
                             compression=zipfile.ZIP_DEFLATED, allowZip64=True)

But the first argument to zipfile.ZipFile is supposed to be "the path to the file, or a file-like object". You're passing a class, which doesn't make any sense. If you want to create an in-memory zipfile, you can pass in another StringIO instance, or you can provide a filename.

Third:

You're not going to be able to write the child_zip object itself to the file; you need to provide some sort of byte stream. In other words, you need to provide the bytes that comprise the child_zip archive.

Putting all this together:

>>> import io
>>> import zipfile
>>> child_zip_data = io.BytesIO()
>>> child_zip = zipfile.ZipFile(child_zip_data, 'w', compression=zipfile.ZIP_DEFLATED, allowZip64=True)
>>> child_zip.close()
>>> parent_zip = zipfile.ZipFile("parent.zip", 'w', compression=zipfile.ZIP_DEFLATED, allowZip64=True)
>>> parent_zip.writestr("test.zip", child_zip_data.getvalue())
>>> parent_zip.close()

This creates a new archive named parent.zip with a single archive member, a file named test.zip :

$ unzip -l parent.zip
Archive:  parent.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
       22  05-29-2020 11:45   test.zip
---------                     -------
       22                     1 file

And if we extract test.zip , we see that it's an empty zipfile:

$ unzip parent.zip
Archive:  parent.zip
  inflating: test.zip
$ unzip -l test.zip
Archive:  test.zip
warning [test.zip]:  zipfile is empty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM