在Zip文件Python中打开文件夹 [英] Opening Folders in Zip Files Python

查看:80
本文介绍了在Zip文件Python中打开文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

zip文件是平坦存储的,每个文件名"都有其自己的内置路径.

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

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

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

这篇关于在Zip文件Python中打开文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆