Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading