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

Python OOP配置字典类运行报错:ValueError: not enough values to unpack

解决ConfigDict类中的ValueError: not enough values to unpack问题

错误原因

你的错误出在key, value = line.split('=', 1)这一行——配置文件Config_file.txt中存在不包含=字符的行(比如空行、仅含空白的行,或者未遵循key=value格式的行)。当split('=',1)执行时,这类行只会返回一个元素,无法被拆成key和value两个变量,因此抛出ValueError。

修复后的代码

以下是加入格式校验和异常处理的完整代码:

import os

class ConfigDict(dict):

    def __init__(self, filename):
        self._filename = filename
        if os.path.isfile(self._filename):
            with open(self._filename) as fh:
                # 遍历行时记录行号,方便定位错误
                for line_num, line in enumerate(fh, 1):
                    line = line.strip()  # 移除行首尾所有空白(换行、空格、制表符)
                    
                    # 跳过空行
                    if not line:
                        continue
                    # 跳过注释行(以#开头,可根据需求修改注释符号)
                    if line.startswith('#'):
                        continue
                    # 检查行是否包含=,避免拆包失败
                    if '=' not in line:
                        print(f"警告:第{line_num}行格式错误,未找到分隔符=,已跳过该行:{line}")
                        continue
                    
                    # 拆分key和value,确保不会报错
                    key, value = line.split('=', 1)
                    # 可选:移除key和value首尾的空白,避免无效空格
                    key = key.strip()
                    value = value.strip()
                    dict.__setitem__(self, key, value)    

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        with open(self._filename, 'w') as fh:
            for key, val in self.items():
                fh.write('{0}={1}\n'.format(key, val))

cd = ConfigDict("Config_file.txt")

关键修改说明

  • 用strip()替代rstrip(),彻底清除行首尾的空白字符,避免空行误判
  • 加入行号计数,方便快速定位配置文件中的格式错误行
  • 增加空行、注释行的跳过逻辑,让配置文件支持更灵活的写法
  • 提前检查行内是否包含=,避免拆包错误,同时给出明确的警告提示
  • 可选对key和value做strip()处理,去除不必要的空白字符

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:09:20