【问题标题】:Can't unzip zip file无法解压缩 zip 文件
【发布时间】:2015-11-25 20:19:27
【问题描述】:

我正在尝试使用 Python 的 zipfile 模块在我的脚本中解压缩一个 zip 文件。问题是当我尝试解压缩此文件时,它会引发Bad magic number for file header error

这是error

..
  zip_ref.extractall(destination_to_unzip_file)
  File "C:\Python27\lib\zipfile.py", line 1040, in extractall
    self.extract(zipinfo, path, pwd)
  File "C:\Python27\lib\zipfile.py", line 1028, in extract
    return self._extract_member(member, path, pwd)
  File "C:\Python27\lib\zipfile.py", line 1082, in _extract_member
    with self.open(member, pwd=pwd) as source, \
  File "C:\Python27\lib\zipfile.py", line 971, in open
    raise BadZipfile("Bad magic number for file header")
zipfile.BadZipfile: Bad magic number for file header

我要解压的文件是这样下载的:

_url = """http://edane.drsr.sk/report/ds_dphs_csv.zip"""

def download_platici_dph(self):
    if os.path.isfile(_destination_for_downloads+'platici_dph.zip'):
        os.remove(_destination_for_downloads+'platici_dph.zip')
    with open(_destination_for_downloads+'platici_dph.zip','w') as f:
        response = requests.get(_url,stream=True)
        if not response.ok:
            print 'Something went wrong'
            return False
        else:
            for block in response.iter_content(1024):
                f.write(block)

有人知道问题出在哪里吗?

【问题讨论】:

  • 您是否尝试过使用其他实用程序解压缩文件以确保它是有效的 ZIP 文件?
  • @MartinEvans 是的,我已经尝试过了,它奏效了。正如 Rob 在他的回答中所说,问题在于下载文件。

标签: python python-2.7 exception zip zipfile


【解决方案1】:

Quoth the documentation for open(): "打开二进制文件时,应在模式值后面加上'b',以二进制模式打开文件"

使用b 为二进制打开输出文件:

with open(_destination_for_downloads+'platici_dph.zip','wb') as f:

【讨论】:

    【解决方案2】:

    我尝试在不使用您的下载代码的情况下下载您的存档,然后使用以下命令解压缩:

    import zipfile
    with zipfile.ZipFile("ds_dphs_csv.zip") as a:
            a.extractall()
    

    效果很好。 zipfile.BadZipfile 异常会在标头出现问题时引发,因此我认为您的文件在下载后已损坏。一定是你的下载方式有问题。

    您可以在这篇文章中找到有关异常的更多详细信息:Python - Extracting files from a large (6GB+) zip file

    【讨论】:

      猜你喜欢
      • 2011-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多