我有這個代碼來解壓縮一個用密碼加密的 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”。如何改進我的代碼?
uj5u.com熱心網友回復:
extractallRuntimeError密碼錯誤時函式會引發,因此您可以執行以下操作
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389947.html
上一篇:**或pow()的Py運算元型別:'list'和'int'
下一篇:“int”物件在佇列中不可下標
