Good handling of input data (was Re: Newbie question)
tgrav at mac.com
Tue Mar 6 11:57:43 CET 2007
On Mar 5, 2007, at 12:47 PM, Larry Bates wrote:
> Tommy Grav wrote:
>> Hi list,
>> this is somewhat of a newbie question that has irritated me for
>> a while.
>> I have a file test.txt:
>> 0.3434 0.5322 0.3345
>> 1.3435 2.3345 5.3433
>> and this script
>> lines = open("test.txt","r").readlines()
>> for line in lines:
>> (xin,yin,zin) = line.split()
>> x = float(xin)
>> y = float(yin)
>> z = float(zin)
>> Is there a way to go from line.split() to x,y,z as floats without
>> each variable individually?
> Using a list comprehension you would write this as:
> for line in lines:
> xin, yin, zin=[float(x) for x in line.split()]
> This if course expects your data to be perfect. If
> you want error handling (e.g. less or more than 3 values,
> values that cause exception when passed to float, etc.)
> you will have to handle that differently.
Thanks for the great response.
So how would you handle this type of error handling?
My main problem is that occasionally there is an entry
in the list that is a string:
0.9834 134.4933 78.009 run11 27
Again I would like to avoid having to individually parse the 3 floats,
while still easily handling the string, but a list comprehension will
not work as far as I can tell. Is there a module that handles this
type of flat ascii tables? Something like:
(x,y,z,id,n) = ParseFile("float","float","float","string","int")
would be great, and I guess
(x,y,z,id,n) = PaseFile2("%f %f %f %s %d")
would be even better.
More information about the Python-list