gpt4 book ai didi

python - 压缩文件 : Check for correct Password

转载 作者:行者123 更新时间:2023-12-05 09:29:43 28 4
gpt4 key购买 nike

我有这段代码可以解压一个用密码加密的 zip 文件:

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"))

它有效,但我希望如果我给函数一个正确的密码,它会提取它并返回例如“True”,或者如果密码错误则返回“False”。我如何改进我的代码?

最佳答案

extractall 函数在密码错误时引发 RuntimeError,因此您可以执行以下操作

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

关于python - 压缩文件 : Check for correct Password,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70451865/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com