Skip to content Skip to sidebar Skip to footer

Opening Folders In Zip Files Python

Is it possible to open a folder located in a zip file and see the names of its contents without unzipping the file? This is what I have so far; zipped_files = zip.namelist()

Solution 1:

Here's an example from a zip i had lying around

>>> from zipfile import ZipFile
>>> zip = ZipFile('WPD.zip')
>>> zip.namelist()
['PortableDevices/', 'PortableDevices/PortableDevice.cs', 'PortableDevices/PortableDeviceCollection.cs', 'PortableDevices/PortableDevices.csproj', 'PortableDevices/Program.cs', 'PortableDevices/Properties/', 'PortableDevices/Properties/AssemblyInfo.cs', 'WPD.sln']

The zip is stored flat, each 'filename' has its own path built in.

EDIT: here's a method i threw together quick to create a sort of structure from the file list

def deflatten(names):
    names.sort(key=lambda name:len(name.split('/')))
    deflattened = []
    while len(names) > 0:
        name = names[0]
        if name[-1] == '/':
            subnames = [subname[len(name):] for subname in names if subname.startswith(name) and subname != name]
            for subname in subnames:
                names.remove(name+subname)
            deflattened.append((name, deflatten(subnames)))
        else:
            deflattened.append(name)
        names.remove(name)
    return deflattened


>>> deflatten(zip.namelist())
['WPD.sln', ('PortableDevices/', ['PortableDevice.cs', 'PortableDeviceCollection.cs', 'PortableDevices.csproj', 'Program.cs', ('Properties/', ['AssemblyInfo.cs'])])]

Post a Comment for "Opening Folders In Zip Files Python"