'Extract archive with "ZipFile" in Python, and get rid of x number of top folders (or specific)

I'm looking for a (simple) way to extract a zip folder, but ignore top folders, or a certain path when extracting.

An example:

   - topdir/subdir/<files and dirs I want>

So I don't want to strip absolutely all directories away, but the top dirs "topdir" and "subdir". I currently have this code:

def extract_zip(zip_file, extraction_path):
    with ZipFile(zip_file, 'r') as archive:
        try: 
            for file in archive.namelist():
                if file.startswith('topdir/subdir/'):
                    archive.extract(file, extraction_path)

The content from "topdir" is now ignored, and I get the content from "subdir" extracted. But the topdir and subdir is still created, with my content inside "subdir".

How can I get the content of subdir (including its subfolders) without creating the topdir/subdir folders?

Would calling 'unzip' be a better alternative?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source