Reading from a file and converting it into a list of lines

John Machin sjmachin at lexicon.net
Tue Jun 6 03:30:52 EDT 2006


On 6/06/2006 4:15 PM, Girish Sahani wrote:
> Really sorry for that indentation thing :)
> I tried out the code you have given, and also the one sreeram had written.
> In all of these,i get the same error of this type:
> Error i get in Sreeram's code is:
> n1,_,n2,_ = line.split(',')
> ValueError: need more than 1 value to unpack
> 
> And error i get in your code is:
> for n1, a1, n2, a2 in reader:
> ValueError: need more than 0 values to unpack
> 
> Any ideas why this is happening?

In the case of my code, this is consistent with the line being empty, 
probably the last line. As my mentor Bruno D. would say, your test data 
does not match your spec :-) Which do you want to change, the spec or 
the data?

You can change my csv-reading code to detect dodgy data like this (for 
example):

for row in reader:
     if not row:
         continue # ignore empty lines, wherever they appear
     if len(row) != 4:
         raise ValueError("Malformed row %r" % row)
     n1, a1, n2, a2 = row

In the case of Sreeram's code, perhaps you could try inserting
     print "line = ", repr(line)
before the statement that is causing the error.


> 
> Thanks a lot,
> girish
> 
> 
> 



More information about the Python-list mailing list