简体   繁体   中英

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()
    print zipped_files
    for folder in zipped_files:
        for files in folder:   #I'm not sure if this works

Does anyone know how to do this? Or do I have to extract the contents?

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'])])]

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