I found one solution that's pretty simple for easy read and write to/from a 
file of a numpy array (see my original message below).  Just use the method 
tolist().

e.g. a complex 2 x 2 array

arr=array([[1.0,3.0-7j],[55.2+4.0j,-95.34]])
ls=arr.tolist()

Then use the repr - eval pairings to write and later read the list from the 
file and then convert the list that is read in back to an array:

[ls_str]=fp.readline()
ls_in= eval(ls_str)
arr_in=array(ls_in)  # arr_in is same as arr

Seems to work well.  Any comments?

-- Lou Pecora,   my views are my own.


--- On Tue, 12/9/08, Lou Pecora wrote:

In looking for simple ways to read and write data (in a text readable format) 
to and from a file and later restoring the actual data when reading back in, 
I've found that numpy arrays don't seem to play well with repr and eval. 

E.g. to write some data (mixed types) to a file I can do this (fp is an open 
file),

  thedata=[3.0,-4.9+2.0j,'another string']
  repvars= repr(thedata)+"\n"
  fp.write(repvars)

Then to read it back and restore the data each to its original type,

        strvars= fp.readline()
        sonofdata= eval(strvars)
        
which gives back the original data list.

BUT when I try this with numpy arrays in the data list I find that repr of an 
array adds extra end-of-lines and that messes up the simple restoration of the 
data using eval.  

Am I missing something simple?  I know I've seen people recommend ways to save 
arrays to files, but I'm wondering what is the most straight-forward?  I really 
like the simple, pythonic approach of the repr - eval pairing.




      
_______________________________________________
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion

Reply via email to