[Numpy-discussion] Use of fromfile

Todd Miller jmiller at stsci.edu
Wed Jun 25 04:02:38 CDT 2003


On Tue, 2003-06-24 at 19:06, Cliff Martin wrote:
> Dear Group,
> 
> I've just started to use numarray as I have an imaging program I want to 
> port.  I noticed in the differences document that one can read in data 
> using fromfile into an array.  This is a great savings over using the 
> standard , string to integer floats.  For some strange reason I can't 
> get it to work correctly with my interferometer file (512,512) array. So 
> I made up a small set of data in a file.(Attached test.txt).
> 

Looking over your test data, it looks like it is in ASCII.  fromfile()
works with binary data.  

Reading in your data can be done with a few lines of Python code:

>>> import numarray
>>> n = numarray.array(shape=(16,), type=numarray.Int32)
>>> f = open("test.txt")
>>> s = f.read()              # Read the whole file as one string
>>> words = s.split(" ")[:-1] # split on spaces; discard trailing junk
>>> for i in range(len(words)):
	n[i] = eval(words[i]) # convert ASCII to Python Ints and assign
>>> n.shape=(4,4)             # Add the "real" shape
>>> n
array([[     0, -32678,     14,     85],
       [   342,     12,     14,     15],
       [    16,     45,     67,     98],
       [    38,    256,    234,    234]])

Binary files are easier and more efficient, but are not portable unless
you remember the byte order. 

Todd

-- 
Todd Miller <jmiller at stsci.edu>





More information about the Numpy-discussion mailing list