ValueError: need more than 0 values to unpack

16,390

It looks like you have lines in your that doesn't actually result in 4 items on splitting. Add a condition for that.

for line in file:
    spl = line.strip().split()
    if len(spl) == 4:  # this will take care of both empty lines and 
                       # lines containing greater than or less than four items
        a, b, c, d = spl
        A.append(a)
        B.append(float(b))
        C.append(float(c))
        D.append(float(d))
Share:
16,390
scrayon
Author by

scrayon

Updated on June 04, 2022

Comments

  • scrayon
    scrayon almost 2 years

    I am new to python and I am trying make a program that reads a file, and puts the information in its own vectors. the file is an xyz file that looks like this:

    45 
    
    Fe -0.055 0.033 -0.047
    N -0.012 -1.496 1.451
    N 0.015 -1.462 -1.372
    N 0.000 1.386 1.481
    N 0.070 1.417 -1.339
    C -0.096 -1.304 2.825
    C 0.028 -1.241 -2.739
    C -0.066 -2.872 1.251
    C -0.0159 -2.838 -1.205
    

    Starting from the 3rd line I need to place each in its own vectors, so far I have this:

    file=open("Question4.xyz","r+")
    A = []
    B = []
    C = []
    D = []
    counter=0
    for line in file:
        if counter>2: #information on particles start on the 2nd line
            a,b,c,d=line.split()
            A.append(a)
            B.append(float(b))
            C.append(float(c))
            D.append(float(d))
        counter=counter+1
    

    I am getting this error:

     File "<pyshell#72>", line 3, in <module>
        a,b,c,d=line.split()
    ValueError: need more than 0 values to unpack
    

    Any ideas on where I am going wrong?

    Thanks in advance!

  • Ashwini Chaudhary
    Ashwini Chaudhary over 11 years
    this will fail for the first line containing '45'.
  • scrayon
    scrayon over 11 years
    Thanks - those extra additions will help
  • Pierre GM
    Pierre GM over 11 years
    @AshwiniChaudhary This won't, as counter = 0 in that case.
  • Pierre GM
    Pierre GM over 11 years
    And... what if len(spl) != 4? Your just skipping the line, without knowing it. Better let your code whine.
  • Ashwini Chaudhary
    Ashwini Chaudhary over 11 years
    then you can add anything in the else part, handle that line in else part.
  • RICHA AGGARWAL
    RICHA AGGARWAL over 7 years
    return type of function does not match with values expected in function... check the number of variables returned from function and variables you are expecting