Why do I get a ValueError when trying to split a line of input and assign to multiple variables?
python
Solution
This is probably because when you're doing the splitting, there is no `:`, so the function just returns one argument, and not 2. This is probably caused by the last line, meaning that you're last line has nothing but empty spaces. Like so:
>>> a = ' '
>>> a = a.strip()
>>> a
''
>>> a.split(':')
['']
As you can see, the list returned from `.split` is just a single empty string. So, just to show you a demo, this is a sample file:
a: b
c: d
e: f
g: h
We try to use the following script (`val.txt` is the name of the above file):
with open('val.txt', 'r') as v:
for line in v:
a, b = line.split(':')
print a, b
And this gives us:
Traceback (most recent call last):
a b
c d
File "C:/Nafiul Stuff/Python/testingZone/28_11_13/val.py", line 3, in <module>
a, b = line.split(':')
e f
ValueError: need more than 1 value to unpack
When trying to look at this through a debugger, the variable `line` becomes `\n`, and you can't split that.
However, a simple logical ammendment, would correct this problem:
with open('val.txt', 'r') as v:
for line in v:
if ':' in line:
a, b = line.strip().split(':')
print a, b
Problem
I tried some code like this to read question and answer pairs from a file: ``` questions_list = [] answers_list = [] with open('qanda.txt', 'r') as questions_file: for line in questions_file: line = line.strip() questions, answers = line.split(':') questions_list.append(questions) answers_list.append(answers) ``` But sometimes I get an exception from the `questions, answers = line.split(':')` line, that says: (Python 2.x) `builtins.ValueError: need more than 1 value to unpack` (Python 3.x) `ValueError: not enough values to unpack (expected 2, got 1)` Alternatively, the opposite problem: `ValueError: too many values to unpack (expected 2)` Why does this occur? How can I fix or work around the problem?