[SciPy-dev] problem with write_array

Pietro Berkes p.berkes at biologie.hu-berlin.de
Wed Oct 9 11:27:03 CDT 2002


Hi! There seem to be a problem with write_array in scipy.io, since it cannot
write 1D or 0D arrays, for example:

>>> import scipy as s
>>> s.__version__
'0.2.0_alpha_133.4174'
>>> a = s.zeros((10,))
>>> a
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> fid = open('file.dat','w')
>>> s.io.write_array(fid,a)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File 
"/home/scipy/local/lib/python2.2/site-packages/scipy/io/array_import.py", 
line 384, in write_array
    array_output=0)
  File 
"/home/scipy/local/lib/python2.2/site-packages/Numeric/ArrayPrinter.py", line 
17, in array2string
    if len(a.shape) == 0:
AttributeError: 'int' object has no attribute 'shape'

The problem in the 1D case is that Numeric.array2string doesn't accept scalar 
quantities as input, while in the 0D case there is an undefined variable. 
Here is my suggestion (should replace function write_array in 
scipy/io/array_import.py):


def write_array(fileobject, arr, separator=" ", linesep='\n',
                precision=5, suppress_small=0):
    """Write a rank-2 or less array to file represented by fileobject.

    Inputs:

      fileobject -- An open file object or a string to a valid filename.
      arr -- The array to write.
      separator -- separator to write between elements of the array.
      linesep -- separator to write between rows of array
      precision -- number of digits after the decimal place to write.
      suppress_small -- non-zero to suppress small digits and not write
                        them in scientific notation.

    Outputs:

      file -- The open file.
    """
      
    file = get_open_file(fileobject, mode='wa')
    rank = len(arr.shape)
    
    if rank > 2:
        raise ValueError, "Can-only write up to 2-D arrays."
    
    if rank == 0:
        h = 1
        rarr = Numeric.reshape(arr, (1,1))
    elif rank == 1:
        h = arr.shape[0]
        rarr = Numeric.reshape(arr, (h,1))
    else:
        h = arr.shape[0]
        
    for k in range(h):
        astr = Numeric.array2string(rarr[k], max_line_width=sys.maxint,
                                    precision=precision,
                                    suppress_small=suppress_small,
                                    separator=' '+separator,
                                    array_output=0)
        astr = astr[1:-1]
        file.write(astr)
        file.write(linesep)
    return file



Greetings,
Pietro.



More information about the Scipy-dev mailing list