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

Python报错ValueError: too many values to unpack (expected 2)求助

问题修复方案

错误原因

ValueError: too many values to unpack (expected 2) 是因为读取credentials.txt后按换行分割得到的元素数量不等于2,常见诱因:

  • 文件内存在多余空行、多组账号密码
  • 行首/行尾有未清理的空白字符
  • 文件格式不符合“第一行邮箱、第二行密码哈希”的预期

代码修复步骤

1. 规范凭证文件格式

credentials.txt必须严格遵循以下格式,无多余空行:

your_email@example.com
your_md5_hashed_password

2. 修正后的完整代码

import hashlib

def login():
    username = input(" Voer uw gebruikersnaam in: ").strip()
    password = input(" Voer uw wachtwoord in: ").strip()
    auth = password.encode()
    auth_hash = hashlib.md5(auth).hexdigest()
    
    with open("credentials.txt", "r") as inlog:
        # 过滤空行并去除每行首尾空白
        lines = [line.strip() for line in inlog if line.strip()]
    
    # 校验文件格式
    if len(lines) != 2:
        print("凭证文件格式错误:请确保文件仅包含两行,第一行是邮箱,第二行是密码哈希")
        return
    
    stored_email, stored_pwd = lines
    if username == stored_email and auth_hash == stored_pwd:
        print(" Succesvol ingelogd!" )
    else:
        print(" Incorrect gebruikersnaam/wachtwoord! \n")

login()

关键修复点

  • 补充hashlib模块导入:原代码遗漏该导入,会触发NameError
  • 修正缩进逻辑:将文件读取代码移入login()函数内部,保证变量作用域正确
  • 处理文件内容:通过列表推导式过滤空行、清理空白字符,避免因格式问题导致分割异常
  • 增加格式校验:提前判断文件行数,给出明确错误提示,避免触发拆包错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:46:01