Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: need more than 1 value to unpack python

Tags:

python

I have got an existing menu that gives you options L or D. L should load the contents of a file and D should display it.

if option == "l" or option == "L":
    with open("packages.txt") as infp:
        for line in infp:
         line = line.rstrip()
         name,adult,child= line.split(',')

if option == "d" or option == "D":
    print ((name)," - ",(adult)," / ",(child))

However, when I try to run this I get the error:

name,adult,child= line.split(',')
ValueError: need more than 1 value to unpack

Why do I get this error?

like image 538
EatMyApples Avatar asked Apr 30 '12 23:04

EatMyApples


2 Answers

This means that there is a line in packages.txt that, when you strip whitespace and split on commas, doesn't give exactly three pieces. In fact, it seems that it gives only 1 piece ("need more than 1 value to unpack"), which suggests that there's a line with no commas at all.

Perhaps there are blank or comment lines in packages.txt?

You may need your code to be smarter about parsing the contents of the file.

like image 138
Gareth McCaughan Avatar answered Oct 19 '22 18:10

Gareth McCaughan


This error is occurring at

name,adult,child= line.split(',')

When you assign three variables on the left it is assuming you have a 3-tuple on the right. In this example, it appears line has no comma hence line.split(',') results in a list with only one string, thus the error "more than 1 value to unpack".

like image 27
bossylobster Avatar answered Oct 19 '22 18:10

bossylobster