Search code examples
pythoncsviterable-unpacking

Unpack only the first few columns from the CSV reader?


When reading a CSV file:

with open("foo.csv") as foo:
    for (a,b) in csv.reader(foo):
        ....

I get the error

ValueError: too many values to unpack

when the file contains more than two columns.

Is there a way to unpack the first two columns and ignore the rest?

I guess I can do

with open("foo.csv") as foo:
    for row in csv.reader(foo):
        a,b = row[0:2]
        ....

but that looks ugly.

PS. I am using python2, if that matters.


Solution

  • Use a generator:

    with open("foo.csv") as foo:
        for a,b in (r[0:2] for r in csv.reader(foo)):
             ...
    

    This more clearly displays your intent. It's basically equivalent to your "ugly" way of doing it, but it's much easier to look at.