在Zip文件Python中打开文件夹

时间:2014-09-12 22:14:31

标签: python python-2.7 zip directory

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

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

有谁知道怎么做?或者我必须提取内容吗?

1 个答案:

答案 0 :(得分:4)

以下是我躺在拉链上的拉链示例

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

拉链存放平,每个'文件名'都有自己的内置路径。

编辑:这是一个方法,我快速拼凑起来从文件列表中创建一种结构

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