[Tutor] Read a data file
ibraheem umaru-mohammed
ium@micromuse.com
Wed, 4 Jul 2001 18:42:43 +0100
[Karim Yaici wrote...]
-| 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
Similar solution using list comprehensions:
>>> import string
>>> f=open('foo.txt')
>>> floats=[ string.split(i.strip(),' ') for i in f.readlines() ]
[['1.02','2.03'], ['3.04','4.05']]
>>>
Kindest regards,
--ibs
--
I know not how I came into this, shall I call it a dying life or a
living death?
-- St. Augustine