我正在尝试使用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)
有谁知道问题出在哪里?
答案 0 :(得分:3)
Quoth the documentation for open()
:" 打开二进制文件时,应将'b'
附加到模式值以二进制模式打开文件"
使用b
为二进制文件打开输出文件:
with open(_destination_for_downloads+'platici_dph.zip','wb') as f:
答案 1 :(得分:1)
我尝试下载您的存档而不使用您的下载代码,然后使用以下代码解压缩
import zipfile
with zipfile.ZipFile("ds_dphs_csv.zip") as a:
a.extractall()
工作得很好。当标题出现问题时会引发异常 zipfile.BadZipfile ,因此我认为您的文件在下载后已损坏。您的下载方法一定存在问题。
您可以在此帖中找到有关例外的更多详细信息:Python - Extracting files from a large (6GB+) zip file