Newbie question

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Mar 5 16:50:04 EST 2007


Tommy Grav a écrit :
> 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  
> converting
> each variable individually?

either map() or a list comprehension

import sys
fname = "test.txt"
lines = open(fname,"r")
for numline, line in enumerate(lines):
   try:
     x, y, z = map(float, line.split())
     # or:
     # x, y, z = [float(item) for item in line.split()]
   except (ValueError, IndexError), e:
     err = "Invalid data format in %s line %s : "%s" (%s)" \
           % (fname, numline, line, e)
     print >> sys.stderr, err
     sys.exit(1)
   else:
     # do whatever appropriate here - anyway

HTH



More information about the Python-list mailing list