ZipFile: Check for correct Password

I have this code to unzip a zip file that is encrypted with a password:

import zipfile

def main(pswd):
    file_name = 'somefile.zip'
    with zipfile.ZipFile(file_name) as file:
       return file.extractall(pwd = bytes(pswd, 'utf-8'))
print(main("password"))

It works, but i want that if I give the function a correct password, it extracts it and returns for example "True", or with a wrong password it returns "False". How can I improve my Code?

>Solution :

extractall function raises RuntimeError when password is bad, so you can do the following

def main(pswd):
    file_name = "somefile.zip"
    with zipfile.ZipFile(file_name) as file:
        try:
            file.extractall(pwd=bytes(pswd, "utf-8"))
            return True
        except RuntimeError:
            return False

Leave a Reply