![](/img/trans.png)
[英]why can't python unzip a password protected zip file created by winrar using the zip method?
[英]Can't unzip zip file
我正在嘗試使用Python的zipfile
模塊在腳本中解壓縮一個zip文件。 問題是,當我嘗試解壓縮該文件時,它Bad magic number for file header error
引發了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)
有人知道問題出在哪里嗎?
查閱open()
的文檔 :“ 打開二進制文件時,應在模式值后附加'b'
以以二進制模式打開文件 ”
使用b
打開輸出文件以獲取二進制文件:
with open(_destination_for_downloads+'platici_dph.zip','wb') as f:
我嘗試不使用下載代碼就下載檔案,然后使用以下命令解壓縮:
import zipfile
with zipfile.ZipFile("ds_dphs_csv.zip") as a:
a.extractall()
工作正常。 標頭中存在問題時會引發異常zipfile.BadZipfile ,因此我認為您的文件在下載后已損壞。 您的下載方法一定有問題。
您可以在這篇文章中找到有關異常的更多詳細信息: Python-從大型(6GB +)zip文件中提取文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.