3
votes

On windows 7, with the newest numpy 1.13.3 and PYTHON 3.5, if I have an array called points, with shape m x 6 and dtype of float32. I can save the array to a "foo.txt" file as below:

np.savetxt('foo.txt', points, fmt='%f %f %f %d %d %d')

but if I run

with open('foo.txt', 'w') as f:
    np.savetxt(f, points, fmt='%f %f %f %d %d %d')

i got the error below:

TypeError Traceback (most recent call last) ~\AppData\Local\Continuum\Anaconda3\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments) 1214 try: -> 1215 fh.write(asbytes(format % tuple(row) + newline)) 1216 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) in () 1 with open('foo.txt', 'w') as f: ----> 2 np.savetxt(f, points, fmt='%f %f %f %d %d %d') 3

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments) 1217 raise TypeError("Mismatch between array dtype ('%s') and " 1218 "format specifier ('%s')" -> 1219 % (str(X.dtype), format)) 1220 if len(footer) > 0: 1221 footer = footer.replace('\n', '\n' + comments)

TypeError: Mismatch between array dtype ('float32') and format specifier ('%f %f %f %d %d %d')

Am I missing anything?

1
write() argument must be str, not bytes, try open('foo.txt', 'wb') - R2RT
savetxt writes bytestrings, so the file needs to be opened accordingly (in Py3). - hpaulj
@R2RT i think you are right, thanks! - shelper

1 Answers

0
votes

This behaviour only happens with Python 3, and depends on the version of numpy.

With older versions of numpy (before 1.14.0) the file must be opened with wb mode to write bytes with savetxt.

With numpy 1.14.0 or later, this issue is resolved. The example in the question works as expected.