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

Maxim Mayzel mayzel at gmail.com
Sat Dec 26 06:47:05 EST 2015


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


More information about the NumPy-Discussion mailing list