【问题标题】:Python zipfile.extract() doesn't extract all filesPython zipfile.extract() 不会提取所有文件
【发布时间】:2013-10-29 07:27:40
【问题描述】:

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

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-内容/
---somefile.php
-wp-config.php
-index.php
在这种情况下,我只获取根文件夹或 wordpress/ 下面的文件夹中的文件。所以我得到了 wordpress/wp-content/somefile.php 但不是 wordpress/ 文件夹本身中的文件。

【问题讨论】:

    标签: python zip extract


    【解决方案1】:

    第一个看的地方是the documentation:

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

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

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

    【讨论】:

    • 2.7.4 及更高版本中似乎存在保护。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      相关资源
      最近更新 更多