13

我正在尝试使用此处找到的代码提取压缩文件夹。

def unzip(source_filename, dest_dir):
with zipfile.ZipFile(source_filename) as zf:

    for member in zf.infolist():
        words = member.filename.split('/')
        path = dest_dir
        for word in words[:-1]:
            drive, word = os.path.splitdrive(word)
            head, word = os.path.split(word)
            if word in (os.curdir, os.pardir, ''): continue
            path = os.path.join(path, word)
        zf.extract(member, path)

但是,例如,当尝试提取具有目录结构
wordpress/
-wp-content/
---somefile.php
-wp-config.php
-index.php的 wordpress.zip 时
,我只能获取根文件夹或 wordpress 下面的文件夹中的文件/ 在这种情况下。所以我得到 wordpress/wp-content/somefile.php 但不是 wordpress/ 文件夹本身中的文件。

4

2 回答 2

24

首先要看的是文档

ZipFile.extractall([path[, members[, pwd]]])

将其应用于您的情况,我会尝试:

def unzip(source_filename, dest_dir):
    with zipfile.ZipFile(source_filename) as zf:
        zf.extractall(dest_dir)
于 2013-10-20T23:21:40.143 回答
1

unzip,定义如下,是你想要的。

def unzip(source_filename, dest_dir):
    with zipfile.ZipFile(source_filename) as zf:
        zf.extractall(dest_dir)
于 2019-06-27T17:36:02.720 回答