[Numpy-discussion] Read array from file
Christopher Barker
Chris.Barker at noaa.gov
Mon Mar 17 13:05:17 EDT 2008
lorenzo bolla wrote:
> what about numpy.loadtxt?
or, probably faster, the little-known (it seems) numpy.fromfile() text mode:
# Read and write the first information lines
for i in range(0,5):
Fdif.write( Fpst.readline() )
# Read and write coordinates
coords =numpy.fromfile(Fpst,
dtype=numpy.float,
sep=' ',
count=nnod*3)
coords.reshape((nnod,3))
By the way, perhaps instead of "overloading" numpy.fromfile(), perhaps
we should just have a separate numpy.fromtextfile() function. Maybe more
people would notice it.
One more note: Even without fromfile() or loadtxt(), you can simplify
your code. Python's "duck typing" and numpy's array-orientation remove a
number of steps:
for i in range(0,nnod):
# Read line
x = Fref.readline() # Read lines
x = x.split() # Split line to strings
x = map ( float,x ) # Convert string elements to floats
no need to make an array -- numpy can work with all python sequences.
#x = array ( x ) # Make an array
# no need to loop == numpy assignment works with sequences:
#for j in range (0,3):
coords[i,:] = x
Or, if you like putting code on one line (and list comprehensions):
for i in range(nnod):
coords[i,:] = [float(x) for x in Fref.readline.split()]
-Chris
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
More information about the NumPy-Discussion
mailing list