简体   繁体   English

Python,ValueError:没有足够的值来解压(预期 2,得到 1),Python OOP

[英]Python, ValueError: not enough values to unpack (expected 2, got 1), Python OOP

In this project, i was told to make a code where i should leverage the convenience of a dictionary to power a configuration file.在这个项目中,我被告知要编写一个代码,我应该利用字典的便利性来为配置文件提供动力。

My following code looks like this:我的以下代码如下所示:

class ConfigDict(dict):

    def __init__(self, filename):
        self._filename = filename
        if os.path.isfile(self._filename):
            with open(self._filename) as fh:
                for line in fh:
                    line = line.rstrip()
                    key, value = line.split('=', 1)
                    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")

The problem arises when i try to run the code, with the specified file name, An error of "ValueError: not enough values to unpack (expected 2, got 1)", from this line of code:当我尝试使用指定的文件名运行代码时出现问题,错误“ValueError: not enough values to unpack (expected 2, got 1)”,来自这行代码:

key, value = line.split('=', 1)

I have searched for solutions regarding this particular problem but have never seem to find it, and your help would really benefit me.我已经搜索了有关此特定问题的解决方案,但似乎从未找到,您的帮助将真正使我受益。

This error is because of a corner case.此错误是由于极端情况造成的。 Suppose line = 'apple' , then key,value = line.split('=', 1) will throw error.Your code is expecting two values but this corner case will return only one value hence the error "Value Error: not enough values to unpack (expected 2, got 1)".假设line = 'apple' ,然后key,value = line.split('=', 1)将抛出错误。您的代码需要两个值,但这种极端情况将只返回一个值,因此错误“值错误:不够要解包的值(预期为 2,得到 1)”。

First, it would be great if you could share a few sample lines from your input file.首先,如果您可以共享输入文件中的一些示例行,那就太好了。

The reason you get the error is because line.split('=', 1) is not returning two values ( key and value ).您收到错误的原因是line.split('=', 1)没有返回两个值( keyvalue )。 What solution to go for depends on what you intend to do with the file. go 的解决方案取决于您打算如何处理该文件。

If you are expecting only 2 values , then keep the code as is and check your files.如果您只期望 2 个值,请保持代码不变并检查您的文件。 I see you already leverage the maxsplit argument, which determines the maximum times to split:我看到您已经利用了maxsplit参数,该参数确定了拆分的最大次数:

key, value = line.split("=", maxsplit=1).

This will not only ensure that only a single split is done but also that it returns a list with 2 elements (at most) or less.这不仅可以确保只完成一次拆分,而且还可以返回一个包含 2 个元素(最多)或更少的列表。 Less is the issue here since the line you are reading doesn't have that many.这里的问题较少,因为您正在阅读的行没有那么多。 Could it be the headline or a line containing other info that cannot be parsed using split ?可能是标题或包含无法使用split解析的其他信息的行? This is important because if you have any corrupt line with more than a single "=" symbol, then a ValueError will be thrown:这很重要,因为如果您有任何带有多个“=”符号的损坏行,则会引发 ValueError:

line = "1=2=3"
key, value = line.split("=")
> ValueError: too many values to unpack (expected 2)

And if you have less, then you will get the error you cited above.如果你有更少,那么你会得到上面提到的错误。

If you have some corrupt lines with only <= 1 value to split , then a good course of action would be to ignore such lines altogether with a try/except block:如果您有一些损坏的行只有 <= 1 的值要 split ,那么一个好的做法是使用 try/except 块完全忽略这些行:

class ConfigDict(dict):

def __init__(self, filename):
    self._filename = filename
    if os.path.isfile(self._filename):
        with open(self._filename) as fh:
            for line in fh:
                line = line.rstrip()
                try:
                   key, value = line.split('=', 1)
                   dict.__setitem__(self, key, value)
                except ValueError:
                   pass

The code above will only set key/value pairs if the split was successful.如果拆分成功,上面的代码只会设置键/值对。

Your code otherwise seems perfectly fine.否则,您的代码似乎非常好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:ValueError:没有足够的值来解包(预期为 3,得到 1) - Python: ValueError: not enough values to unpack (expected 3, got 1) Python ValueError:没有足够的值来解包(预期 3,得到 2) - Python ValueError: not enough values to unpack (expected 3, got 2) Python ValueError:没有足够的值来解压(预期 3,得到 1) - Python ValueError: not enough values to unpack (expected 3, got 1) Python 2-ValueError:没有足够的值可解包(预期6,得到1) - Python 2 - ValueError: not enough values to unpack (expected 6, got 1) Python 3 - ValueError:没有足够的值来解包(预期 3,得到 2) - Python 3 - ValueError: not enough values to unpack (expected 3, got 2) python:ValueError:没有足够的值要解压(预期2,得到0) - python: ValueError: not enough values to unpack (expected 2, got 0) Python,ValueError:没有足够的值来解包(预期 2,得到 1) - Python, ValueError: not enough values to unpack (expected 2, got 1) Python ValueError:没有足够的值来解压(预期 2,得到 1) - Python ValueError: not enough values to unpack (expected 2, got 1) 如何修复ValueError:没有足够的值在python中解包(预期2,得到1)? - How to fix ValueError: not enough values to unpack (expected 2, got 1) in python? Django python ValueError:没有足够的值来解包(预期为 2,得到 1) - Django python ValueError: not enough values to unpack (expected 2, got 1)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM