Python Code to Copy Archive Entry to Stream

Hi,

I need to perform the following task in Python using Aspose.ZIP for Python. Could you please port this C# code to Python? Thanks

if(entry.Name.ToLower().Contains(".zip"))
            {
                // Create memory stream for nested archive
                MemoryStream nestedArchiveStream = new MemoryStream();

                // Copy archive to memory stream
                entry.Open().CopyTo(nestedArchiveStream);

                // Load the nested archive from memory stream
                using (var nestedArchive = new Archive(nestedArchiveStream))
                {
                    // Extract archive to disk.
                    nestedArchive.ExtractToDirectory("Archives/Extracted/"+entry.Name);
                }                               

            }

Hi, please use this Python code as a sample (assumed that the super.zip archive contains nested archives inside):

import aspose.zip as zp
import io

with zp.Archive("super.zip") as archive:
    for entry in archive.entries:
        print("handling entry: "+entry.name)
        if entry.name.lower().endswith(".zip"):
            print("entry is a nested zip archive")
            with io.BytesIO() as nested_stream: 
                print("extracting an entry to the stream")
                entry.extract(nested_stream)
                print("opening extracted stream as archive and ...")
                with zp.Archive(nested_stream) as nested_archive:
                    print("extracting it's content again to "+entry.name+" folder")
                    nested_archive.extract_to_directory("Extracted/"+entry.name)

Please notice, here I’ve used ‘extract()’ to stream instead of ‘open()’ to avoid an extra stream copying

2 Likes