[Numpy-discussion] Problem writing array with savetxt (python3.5)

Julian Taylor jtaylor.debian at googlemail.com
Sat Dec 26 07:24:03 EST 2015


hi
unfortunately numpy text io in python3 is very broken and best avoided.
Technically you might be able to work around it by opening the file in
binary mode but that is the wrong way of doing it and might break when
we finally get around to really fixing it, also won't work for unicode
and string containing escape characters (e.g. windows filenames).


On 12/26/2015 12:47 PM, Maxim Mayzel wrote:
> Dear all,
> 
> I’m having a problem writing an array with np.savetxt, see below.
> (python3.5, numpy 1.10.1)
> 
> import numpy as np
> a=np.ones(5,dtype=int)
> np.savetxt('t.txt',a)
> 
> Works fine, but the content of ’t.txt’ is overwritten. 
> But, passing file handle gives an error, while it works fine on python2.7 !
> 
> 
> with open('t.txt','w') as t:
>    np.savetxt(t,a,fmt='%i')
>   ...:
> ---------------------------------------------------------------------------
> TypeError                                 Traceback (most recent call last)
> /Users/may/anaconda/lib/python3.5/site-packages/numpy/lib/npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments)
>   1155                 try:
> -> 1156                     fh.write(asbytes(format % tuple(row) + newline))
>   1157                 except TypeError:
> 
> TypeError: write() argument must be str, not bytes
> 
> During handling of the above exception, another exception occurred:
> 
> TypeError                                 Traceback (most recent call last)
> <ipython-input-4-cce5156eb1e6> in <module>()
>      1 with open('t.txt','w') as t:
> ----> 2     np.savetxt(t,a,fmt='%i')
>      3
> 
> /Users/may/anaconda/lib/python3.5/site-packages/numpy/lib/npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments)
>   1158                     raise TypeError("Mismatch between array dtype ('%s') and "
>   1159                                     "format specifier ('%s')"
> -> 1160                                     % (str(X.dtype), format))
>   1161         if len(footer) > 0:
>   1162             footer = footer.replace('\n', '\n' + comments)
> 
> TypeError: Mismatch between array dtype ('int64') and format specifier ('%i’)
> 
> 
> Best,
> Dr. Maxim Mayzel
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> https://mail.scipy.org/mailman/listinfo/numpy-discussion
> 




More information about the NumPy-Discussion mailing list