I was bitten by the following numpy behaviour:
In [234]: savetxt(open('/tmp/a.dat', 'wt'), array([1, 2, 3]))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-234-2adef92da877> in <module>()
----> 1 savetxt(open('/tmp/a.dat', 'wt'), array([1, 2, 3]))
/local/gerrit/python3.2/lib/python3.2/site-packages/numpy/lib/npyio.py in savetxt(fname, X, fmt, delimiter, newline)
1007 else:
1008 for row in X:
-> 1009 fh.write(asbytes(format % tuple(row) + newline))
1010 finally:
1011 if own_fh:
TypeError: must be str, not bytes
In [235]: savetxt(open('/tmp/a.dat', 'wb'), array([1, 2, 3]))
# success
I find this strange. I’m trying to save my array to a text file. Then why should I open the file in binary mode?
Because your data is bytes (ie binary) data.
What comes out is still a text file. Don’t worry. 🙂 A “text” file is defined a something that contains only human readable text, not by in which mode you open it. The mode just makes a difference in how it handles the data given.
Text mode means it expects Unicode data, and it will encode it into bytes format for you. Binary mode means it expects data in bytes, and will not encode it.