ValueError: too many values to unpack

John Machin sjmachin at lexicon.net
Wed Apr 11 16:14:38 EDT 2007


On Apr 12, 5:28 am, "fscked" <fsckedag... at gmail.com> wrote:
> On Apr 11, 10:26 am, Laszlo Nagy <gand... at designaproduct.biz> wrote:
>
>
>
> > fscked írta:> Trying to use CSV to read in a line with 11 fields and I keep getting
> > > this error. I have googled a bit and have been unable to figure it out.
>
> > Probably you have more than 11 values in some (or all) of the rows in
> > the CSV file. Try this code:
>
> > L = (1,2,3,4,5)
> > a1,a2,a3 = L
>
> > If you are sure that you only need a certain number of values, "the
> > first N columns":
>
> > a1,a2,a3 = L[:3]
>
> > Then you still can have a "not enough values to unpack" error, guess
> > what that means. ;-)
>
> >    Laszlo
>
> Hmm, well I have counted the fields in the CSV and verified there are
> only 11.

Counted how? Checked each line in the file? Let Python do it; see
below.

> Here is the offending code:
>
> myfile = open('ClientsXMLUpdate.csv')

Put in a second arg of 'rb'; if not the case now, someone might run
your code on Windows some day.

What platform, what version of Python?

> csvreader = csv.reader(myfile)
>
> for boxid, mac, activated, hw_ver, sw_ver, heartbeat, name, address,
> phone, country, city in csvreader:

Not exactly bullet-proof code.

> I just don't get it... :/

Possibly (in one or more rows) the address field has a comma in it and
it's not quoted properly.

Try writing your code in a more defensive fashion:
ENCOLS = 11
rownum = 0
for row in csvreader:
    rownum += 1
    ancols = len(row)
    if ancols != ENCOLS:
        print "Row %d has %d columns (expected %d)" \
            % (rownum, ancols, ENCOLS)
        print row
        # pass/return/continue/break/raise/call error logger .....
    (boxid, mac, activated, hw_ver,
    sw_ver, heartbeat, name, address,
    phone, country, city) = row

HTH,
John




More information about the Python-list mailing list