Aman Grover Aman Grover - 3 months ago 31
Python Question

zipfile.extractall always gives exception

Here is my script:

import zipfile
zFile = zipfile.ZipFile('crack.zip')
passFile = open('passwords.txt')
for line in passFile.readlines():
password = line.strip('\n')
try:
zFile.extractall(pwd=password)
print password
except Exception, e:
print e


These are the contents of passwords.txt:

abcde
fghijk
secret
lmnopq
rstw
uvwxyz


The file passwords.txt has 5 strings, out of which only one is the correct password for this zip file(As you would have guessed, secret is the correct password). When I run this script , it always goes to the catch block and prints
('Bad password for file', <zipfile.ZipInfo object at 0x7f70836d52a8>)
5 times. What am I doing wrong here?

Answer

After you successfully unzip the file with the right password, you don't stop the loop. Therefore it continues and tries the other three passwords. There are five incorrect passwords in your file so you get five exceptions. To fix this, add a break statement. I rearranged your code a bit, because generally, only the statement you want to catch exceptions in should be in the try block.

for line in passFile:
    password = line.strip()
    print password
    try:
        zFile.extractall(pwd=password)
    except Exception, e:
        print e
    else:
        print "success"
        break
Comments