You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用7z批量解压带密码压缩包报找不到文件错误如何解决

问题根源

报错是几个核心问题共同导致的:

  • 7z命令行参数格式错误
    -p参数和密码之间不能有空格,必须直接拼接。你当前代码把'-p'和密码拆成了两个独立参数传递,7z会将-p识别为「使用空密码」,紧接着的密码值(第一次循环时是zip)会被7z识别为待解压的压缩包文件名。当前目录下不存在名为zip的文件,就触发了你看到的「找不到文件zip」的报错。
  • 路径读取逻辑有隐藏bug
    你计算了脚本所在的绝对路径dirPath,但后续调用os.listdir()、读取passwords.txt、调用7z.exe时都用了相对路径,如果你运行脚本时的终端工作目录和脚本存放目录不一致,会出现找不到压缩包、找不到密码文件、找不到7z程序的问题。
  • 分卷压缩包识别逻辑失效
    os.path.splitext()对xxx.7z.001这类分卷文件提取的后缀是.001,你写的ext == '7z.001'判断永远不会成立,无法识别7z分卷包。
修复后的完整代码
import subprocess
import os

currentFile = __file__
realPath = os.path.realpath(currentFile)
dirPath = os.path.dirname(realPath)
# 切换工作目录到脚本所在目录,彻底解决相对路径找不到文件的问题
os.chdir(dirPath)

sevenz = os.path.join(dirPath, 'binaries', '7z.exe')
files = []

for filename in os.listdir(dirPath):
    # 跳过目录,只处理文件
    if not os.path.isfile(filename):
        continue
    ext = os.path.splitext(filename)[-1].lower()
    if ext in ('.rar', '.zip', '.7z'):
        files.append(filename)
    # 修正分卷7z的判断逻辑
    if filename.endswith('.7z.001'):
        files.append(filename)           

with open('passwords.txt', 'r', encoding='utf-8') as f:
    passwords = [line.rstrip('\n') for line in f if line.strip()]

# 优化解压逻辑:按文件遍历密码,解压成功即停止试错,避免重复解压
for file in files:
    print(f'正在处理压缩包: {file}')
    extract_success = False
    for password in passwords:
        # 核心修复:-p和密码直接拼接,不拆成独立参数
        result = subprocess.run(
            [sevenz, 'x', '-y', f'-p{password}', file],
            capture_output=True
        )
        if result.returncode == 0:
            print(f'  解压成功,使用密码: {password}')
            extract_success = True
            break
    if not extract_success:
        print(f'  解压失败,passwords.txt中没有匹配的密码')
额外说明
  • 代码加了解压结果判断,每个压缩包找到正确密码后就会停止尝试剩余密码,不会重复解压
  • 读取passwords.txt时加了空行过滤,避免文件里的空行被当成密码尝试
  • 用os.path.join拼接路径,兼容Windows不同路径分隔符的写法
  • 遍历文件时跳过了子目录,避免把文件夹名当成压缩包处理

内容的提问来源于stack exchange,提问作者Vader

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 05:31:36