Ryan D. Ryan D. - 1 year ago 202
Python Question

ValueError Expected 2 Got 1 Python

I'm trying to read the following data into my program.

Distance (m) Mass (kg)
0.0865 0.1
0.1015 0.15
0.4416 0.9
0.4304 0.95
0.437 1.0

I'm using the following code, which is straight out of the book.

def getData(fileName):
dataFile = open(fileName, 'r')
distances = []
masses = []
discardHeader = dataFile.readline()
for line in dataFile:
d, m = line.split(' ')
return (masses, distances)

The code consistently returns:

ValueError: not enough values to unpack (expected 2, got 1)

I've looked at other ValueError entries, here and on the web, that pertain to reading space-separated data into a program, but have yet to find one with a substantially similar problem.

I conjecture that the problem is the line
d, m = line.split(' ')
. I'm not sure what this is called (compound assignment? tuple assignment?), why it's not working (I've never tried it this way before, but it seems reasonable), or how to make it work. If anyone who has approached reading in a file this way could shed some light on the situation, it would be greatly appreciated.

Answer Source

This is called unpacking. When you have an iterable (list, tuple, or anything that supports indexing), a syntax like x, y = point gets the point[0], point[1] elements and assigns them to x, y respectively. However, if there is no point[0] or point[1] it will throw an exception

That is what happens in your case, most probably because some line in your file is missing a space between the two values, so line.split(' ') returns just one thing

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download