在 Python 中打开 Zip 文件中的文件夹

Kev*_*vin 0 python directory zip python-2.7

是否可以在不解压缩文件的情况下打开 zip 文件中的文件夹并查看其内容的名称?这就是我到目前为止所拥有的;

    zipped_files = zip.namelist()
    print zipped_files
    for folder in zipped_files:
        for files in folder:   #I'm not sure if this works
Run Code Online (Sandbox Code Playgroud)

有谁知道如何做到这一点?或者我必须提取内容?

use*_*282 5

这是我放在身边的拉链的一个例子

>>> 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']
Run Code Online (Sandbox Code Playgroud)

zip 是扁平存储的,每个“文件名”都有自己的内置路径。

编辑:这是我快速组合在一起的一种方法,可以从文件列表中创建一种结构

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'])])]
Run Code Online (Sandbox Code Playgroud)