reading floats from file

Pete Shinners pete at visionart.com
Tue Sep 4 18:52:42 EDT 2001


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]))


strings already have a split() method that will split
the string based on whitespace. no need to bring RE into
the mix for this.

for line in fh.readlines():
     x = map(float, line.split())




More information about the Python-list mailing list