Search code examples
pythonpython-3.xunpack

Values: too many values to unpack (expected 18)


I am trying to accomplish three things with the code but I keep getting stuck on the first step:

  1. Cleared lists for every column in the csv file. Specifically for indicator geocode geoarea timeperiod and value. Here I keep getting the too many values to unpack error. There are 18 columns. I tried including try and except but then my list was limited to 384 lines when there is way more. Do you have any ideas for workarounds?

  2. Create lists for every line

  3. Filter and select lists for the most recent year 2015

Here is the data that I have been working with: https://github.com/guillermocubells/sdg9b1_642

innovation_9b1 = open('Indicators_9_6.csv','r' , encoding = 'utf-8' , errors= 'ignore') 

innovation_9b1.readline()
indicator= []
geocode = []
geoarea = []
timeperiod= []
value = []  
for lines in innovation_9b1:
    _,_,i,_,_,g,a,tp,v,_,_,_,_,_,_,_,_,_,= lines.strip().split(',')
    indicator.append(i)
    geocode.append(g)
    geoarea.append(a)
    timeperiod.append(tp)
    print(lines)

Solution

  • Given the variables you are using you would be better off like this:

    for lines in innovation_9b1:
        elements = lines.strip().split(',')
        indicator.append(elements[2])
        geocode.append(elements[5])
        geoarea.append(elements[6])
        timeperiod.append(elements[7])
        print(lines)