reading floats from file

Edward S. Vinyard Edward.S.Vinyard at jpl.nasa.gov
Tue Sep 4 18:11:40 EDT 2001


Try this...

import string

def fileToMatrix(file_name):
    file = open(file_name, 'r')
    lineToRow = lambda line: map(float, string.split(line))
    return map(lineToRow, file.readlines())

Cheers,
Ed

John Hunter wrote:
> 
> I have a file of ascii data arranged as a matrix of floats, eg
> 
> 0.3125 0.9418 1.2843 0.924516 0.92855
> 0.3125 0.6593 1.2843 0.900514 0.900914
> 0.1667 0.9757 1.5611 0.893318 0.893699
> 
> I want to read this data and process it a line at a time
> 
> This works:
> 
> fh = open(dataDir + 'freqs_and_amps.dat')
> for line in fh.readlines():
>     line = re.sub('^[ ]+', '', line)
>     x = map(float, re.split('[\r\n\t ]+', line[0:len(line)-1]))
> 
> 
> But I suspect there is a better way.
> 
> Suggestions?
> 
> Thanks,
> John Hunter
> 




More information about the Python-list mailing list