The zipfile module checks for this as well as it can it returns a 'Bad password for file' when the password doesn't match.
But it does this on a per file basis. As each file in a ZIP file can have its own different password which was the password that was given when the file was added to the archive.
I think that your zip file was not password protected as zipfile accepts a password when extracting for files that aren't password protected. It does not report an error when the password is not used because the file was not password protected.
To avoid extracting a zip file that is not password protected when a password is provided one has check if the files are password protected:
import zipfile
def all_files_are_password_protected(zf):
return all(zinfo.flag_bits & 0x1 for zinfo in zf.infolist())
zFile=zipfile.ZipFile("important.zip")
try:
if all_files_are_password_protected(zFile):
zFile.extractall(pwd="oranges")
except Exception as e:
import traceback
traceback.print_exc()
Based on:
zf = zipfile.ZipFile(archive_name)
for zinfo in zf.infolist():
is_encrypted = zinfo.flag_bits & 0x1
if is_encrypted:
print '%s is encrypted!' % zinfo.filename
From How to check if a zip file is encrypted using python's standard library zipfile?
Note that every file has their own password so some files might fail to be extracted if encrypted with a different password.