在 ZipFile.setpassword 命令中使用变量

using a variable with the ZipFile.setpassword command

我正在为我的 class 编写脚本以打开受密码保护的 zip 文件。我有一个需要循环的密码列表。

我创建了一个脚本,当我在密码字段中手动输入密码时,它可以完美地执行该功能:ZipFile.setpassword(b'12345')

但是我想要做的是使用变量 passwordattempt 来代替它循环遍历我列表的每个条目,就像这样 ZipFile.setpassword (b'passwordattempt') 但是当我这样做时它永远不会工作并且似乎没有使用分配给变量的密码。

我可以看到它通过使用 print(passattempt)

正确地遍历了我的列表
#################################
## Create a temp list of pass  ##
## words from the allpass.txt  ##
## file                        ##
#################################

#Create a temp Library
passwordlib = []

#Open temp allpassword file to put into temp list
with open('allpass.txt', 'r+') as f:
    for line in f:
        line = line.rstrip("\n")
        #print(line)
        passwordlib.append(line)
f.close()
#End of temp list creation


#Attempt to open zip file using the list of passwords in passwordlib[]
for line in passwordlib:
        passattempt = line.strip('\n')
        try:
          zip_ref = zipfile.ZipFile("Resources/ZippedFiles/testzip.zip", 'r')
          print (passattempt) #Print to confirm passwords are cycling through
          zip_ref.setpassword(b'passattempt')            
          zip_ref.extractall("Resources/ZippedFiles/testout/")
        except:
          pass #if password is incorrect, ignore Runtime error and move to next password      
        zip_ref.close()

是的,只需使用 encode 使用默认编码 (utf-8) 将 string 转换为 bytes

import zipfile

with open('allpass.txt', 'r+') as f:
    passwordlib = f.readlines()

# Attempt to open zip file using the list of passwords in passwordlib[]
for line in passwordlib:
    passattempt = line.strip('\n')
    with zipfile.ZipFile("file.zip", 'r') as zf:
        print(passattempt)  # Print to confirm passwords are cycling through
        zf.setpassword(passattempt.encode())
        try:
            zf.extractall("Resources/ZippedFiles/testout/")
        except RuntimeError as e:
            if 'Bad password' not in str(e):
                raise