三二互联专业提供速度最快最稳定的美国服务器、香港服务器。中美直连,亚洲优化![ 代理登陆 ] [ 付款方式 ] [ 找回密码 ][ 电子协议责任书 ]
硬件资源保障

采用高配品牌服务器

主流强悍CPU配置

确保服务高速稳定运行

中美直连线路

中美直连亚洲优化

采用中国CN2骨干网络

保证速度飞快稳定高效

尝试解压密码保护的zip文件时,如果密码错误,如何给出提示信息?

美国、香港服务器

尝试解压密码保护的zip文件时,如果密码错误,如何给出提示信息?

05-08   来源:

 在使用 Python 的 zipfile 模块尝试解压密码保护的 ZIP 文件时,若密码错误,可通过捕获 RuntimeError 异常并检查异常信息来给出提示。下面是不同场景下(单个文件解压、批量文件解压)的示例代码:

单个文件解压
python
import zipfile
 
 
def unzip_single_password_protected_file(zip_file_path, password, extract_path):
    try:
        with zipfile.ZipFile(zip_file_path, "r") as zip_ref:
            zip_ref.setpassword(password.encode())
            zip_ref.extractall(extract_path)
        print(f"成功解压 {zip_file_path} 到 {extract_path}")
    except FileNotFoundError:
        print(f"错误:未找到 {zip_file_path} 文件。")
    except zipfile.BadZipFile:
        print(f"错误:{zip_file_path} 不是有效的 ZIP 文件。")
    except RuntimeError as e:
        if "Bad password for file" in str(e):
            print(f"错误:{zip_file_path} 的密码错误,请检查密码。")
        else:
            print(f"发生未知错误:{e}")
 
 
# 示例用法
zip_file = "example.zip"
password = "wrong_password"
extract_path = "extracted"
unzip_single_password_protected_file(zip_file, password, extract_path)
 
 
 
 
 
代码解释
当调用 extractall 方法时,如果密码错误,会抛出 RuntimeError 异常。
通过检查异常信息中是否包含 Bad password for file 来判断是否是密码错误,若是则给出相应提示。
批量文件解压
python
import os
import zipfile
import pathlib
 
 
def batch_unzip_password_protected_files(zip_dir, password, extract_dir):
    zip_dir = pathlib.Path(zip_dir)
    extract_dir = pathlib.Path(extract_dir)
    extract_dir.mkdir(parents=True, exist_ok=True)
 
    for zip_file_path in zip_dir.rglob("*.zip"):
        try:
            with zipfile.ZipFile(zip_file_path, "r") as zip_ref:
                zip_ref.setpassword(password.encode())
                file_extract_dir = extract_dir / zip_file_path.stem
                file_extract_dir.mkdir(parents=True, exist_ok=True)
                zip_ref.extractall(file_extract_dir)
            print(f"成功解压 {zip_file_path} 到 {file_extract_dir}")
        except FileNotFoundError:
            print(f"错误:未找到 {zip_file_path} 文件。")
        except zipfile.BadZipFile:
            print(f"错误:{zip_file_path} 不是有效的 ZIP 文件。")
        except RuntimeError as e:
            if "Bad password for file" in str(e):
                print(f"错误:{zip_file_path} 的密码错误,请检查密码。")
            else:
                print(f"发生未知错误:{e}")
 

三二互联专业提供香港VPS,美国VPS主机,香港云服务器租用等业务香港美国到大陆CN2 GIA速度最快

上一篇:如何优化密码错误时的提示信息? 下一篇:如何使用Python批量解压密码保护的zip文件?

美国GIA服务器三二互联版权所有 WWW.222.cc 2008-2015 All Rights Reserved
三二互联 - 专业的美国C3服务器香港vps、抗DOOS流量清洗、云备份系统、网站加速系统、美国GIA服务器和香港云服务器产品提供商
三二互联24小时在线工单系统为您提供全面、专业、周到的技术支持与服务
咨询热线:400-679-9994(免长话费)