Python zipfile.extract() 无法提取所有文件

14

我正在尝试使用在这里找到的代码来解压缩文件夹。

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.zip文件时:
wordpress/
-wp-content/
---somefile.php
-wp-config.php
-index.php
我只能获取根目录或者在这种情况下是wordpress/文件夹下的文件。所以我可以获取wordpress/wp-content/somefile.php, 但无法获取wordpress/文件夹中的文件。

2个回答

25

第一个查找的地方是文档

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

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

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

1
看起来保护措施存在于2.7.4及更高版本。 - Robᵩ

1
"

unzip

",如下所定义,是你想要的。
def unzip(source_filename, dest_dir):
    with zipfile.ZipFile(source_filename) as zf:
        zf.extractall(dest_dir)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接