我最近一直在使用拉链式粗暴器。
我的问题是,当我运行代码时,它会覆盖提取的文件。 成功提取文件后,它不会停止。
所以我想在成功提取文件时退出循环,但我无法找到解决方法。
有什么想法吗?
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()
答案 0 :(得分:1)
如果您成功extractall
,您希望break
退出循环:
for x in L:
try:
zip_file = zipfile.ZipFile(zipfilename)
zip_file.extractall("extracting_directory",pwd=x)
break
except:
pass
答案 1 :(得分:0)
例如,在您的try:
zip_file = zipfile.ZipFile(zipfilename)
zip_file.extractall("extracting_directory",pwd=x)
except Exception:
pass
else:
break
和else
循环中添加一个else分支:
try
如果break
- 块完成没有任何异常,则执行try
- 块。您也可以将{{1}}添加到{{1}} - 结尾处。