ValueError: requires more than 1 value to decompress python

I have an existing menu that gives you options L or D L should load the contents of the 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 an error:

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

Why am I getting this error?

+7
source share
3 answers

This means that packages.txt has a line that, when you separate spaces and separate commas, does not give exactly three parts. In fact, it seems that it gives only 1 part ("you need more than 1 value to unpack"), which means that there is a line without commas at all.

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

You may need to make your code smarter to parse the contents of the file.

+12
source

This error occurs when

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

When you assign three variables on the left, it is assumed that you have a 3-tuple on the right. In this example, it seems that line does not have a comma, so line.split(',') leads to a list with only one line, so the error is "more than 1 value to unpack".

+3
source

line.split(',') returns a tuple. You can then pack this tuple by writing:

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

If the tuple does not have exactly three elements, then unsuccessful packaging is not performed. In your case, the error message indicates that you have only one item. So line.split(',') explicitly returns a tuple with only one element. This means that line has no commas.

Perhaps this means that your input is not what you expect. You require that line be a string containing three values ​​separated by commas, but there is a string in your input that does not meet this requirement.

+2
source

All Articles