String Fomat Conversion

Steven Bethard steven.bethard at gmail.com
Thu Jan 27 08:02:45 CET 2005


Stephen Thorne wrote:
> f = file('input', 'r')
> labels = f.readline() # consume the first line of the file.
> 
> Easy Option:
> for line in f.readlines():
>   x, y = line.split()
>   x = float(x)
>   y = float(y)
> 
> Or, more concisely:
> for line in f.readlines():
>   x, y = map(float, line.split())

Somewhat more memory efficient:

lines_iter = iter(file('input'))
labels = lines_iter.next()
for line in lines_iter:
     x, y = [float(f) for f in line.split()]

By using the iterator instead of readlines, I read only one line from 
the file into memory at once, instead of all of them.  This may or may 
not matter depending on the size of your files, but using iterators is 
generally more scalable, though of course it's not always possible.

I also opted to use a list comprehension instead of map, but this is 
totally a matter of personal preference -- the performance differences 
are probably negligible.

Steve



More information about the Python-list mailing list