5

我正在使用当前代码从 zip 文件中提取文件,同时保持目录结构:

zip_file = zipfile.ZipFile('archive.zip', 'r')
zip_file.extractall('/dir/to/extract/files/')
zip_file.close()

这是示例 zip 文件的结构:

/dir1/file.jpg
/dir1/file1.jpg
/dir1/file2.jpg

最后我想要这个:

/dir/to/extract/file.jpg
/dir/to/extract/file1.jpg
/dir/to/extract/file2.jpg

但是只有当 zip 文件有一个包含所有文件的顶级文件夹时它才应该忽略,所以当我提取具有这种结构的 zip 时:

/dir1/file.jpg
/dir1/file1.jpg
/dir1/file2.jpg
/dir2/file.txt
/file.mp3

它应该保持这样:

/dir/to/extract/dir1/file.jpg
/dir/to/extract/dir1/file1.jpg
/dir/to/extract/dir1/file2.jpg
/dir/to/extract/dir2/file.txt
/dir/to/extract/file.mp3

有任何想法吗?

4

3 回答 3

6

如果我正确理解您的问题,您希望在提取之前从 zip 中的项目中删除任何常见的前缀目录。

如果是这样,那么下面的脚本应该做你想做的事:

import sys, os
from zipfile import ZipFile

def get_members(zip):
    parts = []
    # get all the path prefixes
    for name in zip.namelist():
        # only check files (not directories)
        if not name.endswith('/'):
            # keep list of path elements (minus filename)
            parts.append(name.split('/')[:-1])
    # now find the common path prefix (if any)
    prefix = os.path.commonprefix(parts)
    if prefix:
        # re-join the path elements
        prefix = '/'.join(prefix) + '/'
    # get the length of the common prefix
    offset = len(prefix)
    # now re-set the filenames
    for zipinfo in zip.infolist():
        name = zipinfo.filename
        # only check files (not directories)
        if len(name) > offset:
            # remove the common prefix
            zipinfo.filename = name[offset:]
            yield zipinfo

args = sys.argv[1:]

if len(args):
    zip = ZipFile(args[0])
    path = args[1] if len(args) > 1 else '.'
    zip.extractall(path, get_members(zip))
于 2012-01-01T04:54:00.350 回答
1

这可能是 zip 存档本身的问题。在 python 提示符下尝试此操作以查看文件是否位于 zip 文件本身的正确目录中。

import zipfile

zf = zipfile.ZipFile("my_file.zip",'r')
first_file = zf.filelist[0]
print file_list.filename

这应该说类似“dir1”的内容重复上述步骤,将 1 替换和索引到文件列表中,这样first_file = zf.filelist[1]这次输出应该看起来像“dir1/file1.jpg”,如果不是这种情况,那么 zip 文件不包含目录和将全部解压缩到一个目录中。

于 2011-12-31T20:14:44.880 回答
1

读取由返回的条目ZipFile.namelist()以查看它们是否在同一目录中,然后打开/读取每个条目并将其写入使用open().

于 2011-12-31T18:54:31.960 回答