[Tutor] Read a data file

Karim Yaici karimy@nipltd.com
Wed, 4 Jul 2001 16:53:03 +0100


Hi Carole,

> I would like to read a data file like this one:
>
> x1 y1
> x2 y2
> x3 y3
> ...
>
> (each line contains 2 float values)
> I want to read each value separately.
> How can I do this?

That's an easy one ;-)

Here is a quick solution. Warning untested code ;-)

import string

def line2floats(theLine):
  # useful to convert a string to a tuple of floats
  f1,f2 = string.split(string,strip(theLine),' ')
 return float(f1),float(f2)

file = open('data.txt','rb')
lines= file.readlines() # this should return a list of string, one string
per line.
floats = map(lambda eachLine: line2floats(eachLine), lines) # line2floats is
defined below..

print floats

so if you had:
1.02 2.03
3.04 4.05

floats will be equal to [(1.02,2.03),(3.04,4.05)]

I hope this will help you

Cheers,
Karim