Extract zip, truncate enclosed directory

Sometimes you want to unpack the contents of an archive. Sometimes the files in that particular archive are contained in a subfolder, so they won't spam the folder you're extracting it to. This has become good practice in a lot of archives.

But what if you need the files inside the archive, without the enclosing folder(s), i.e. for redistribution or building something else?

Python's ZipFile allows you to specify a destination, but each member of the archive will still be extracted with it's full path relative to that folder. So here is a little hack:

def d_zip(filename, dest=".", strip_levels=1):
    # create the zipfile object
    zfile = ZipFile(filename) 

    tmpdir = tempfile.gettempdir()
    for zip_path in zfile.namelist():
        # truncate the path, dropping dirs from the start on the /-split string
        truncated_path = os.path.sep.join(zip_path.split(os.path.sep)[strip_levels:])
        # now, join to the dest so we got a new destination path
        dest_path = os.path.join(dest, truncated_path)
        # extract the file, store resulting path
        extracted_path = zfile.extract(zip_path, tmpdir)
        # Paths must exist when moving. Let's make sure that is the case.
        dest_dir = os.path.dirname(dest_path) 
        if not os.path.isdir(dest_dir):
            os.makedirs(dest_dir)
        # Moving the files only. We got the directories covered.
        if not os.path.isdir(extracted_path):
            os.rename(extracted_path, dest_path)