当前位置: 动力学知识库 > 问答 > 编程问答 >

How can I exit the loop when the zip file is extracted successfully in Python

问题描述:

I've been working lately on a zip brute-forcer.

My problem is that when I run the code it overwrites the extracted file.

It doesn't stop when the file is successfully extracted.

So I want to exit the loop when the file successfully extracted, but I couldn't find a way around it.

Any ideas?

import sys

import zipfile

import os

L = ['password1','password2','password3','password4','password5']

zipfilename = 'file.zip'

#loop through the passwords list and try to extract the file

for x in L:

try:

zip_file = zipfile.ZipFile(zipfilename)

zip_file.extractall("extracting_directory",pwd=x)

#ignore errors "wrong password attempts stops the loop"

except:

pass

#list all files in the dir to make sur u extracted it successfully

x = os.listdir("extracting_diectory")

print x

#read the output file

fh = open('/extracting_directory/myfile.txt','r')

print fh.read()

网友答案:

Add, for instance, an else-branch to your try-except and break the loop:

try:
    zip_file = zipfile.ZipFile(zipfilename)
    zip_file.extractall("extracting_directory",pwd=x)
except Exception:
    pass
else:
    break

The else-block is executed if the try-block finished without any exception. You could also add the break to the end of your try-block here.

网友答案:

If you successfully extractall you want to break out of the loop:

for x in L:
    try:
        zip_file = zipfile.ZipFile(zipfilename)
        zip_file.extractall("extracting_directory",pwd=x)
        break
    except:
        pass
分享给朋友:
您可能感兴趣的文章:
随机阅读: