简体   繁体   English

在Zip文件Python中打开文件夹

[英]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? 是否可以在不解压缩文件的情况下打开位于zip文件中的文件夹并查看其内容的名称? 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. zip文件是平面存储的,每个“文件名”都有自己的内置路径。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM