I'm trying to save a numpy matrix (Nx3, float64) into a txt file using numpy.savetxt:
Dictionary<string, Foo>
This line worked in python 2.7, but in python 3.5, I'm getting the following error:
TypeError: Mismatch between array dtype ('float64') and format specifier ('%.5f %.5f %.5f')
When I'm stepping into the savetxt code, the print the error (traceback.format_exc()) in the catch block (numpy.lib.npyio, line 1158), the error is completely different:
TypeError: write() argument must be str, not bytes
The line of code resulting the exception is the following:
np.savetxt(f, mat, fmt='%.5f', delimiter=' ')
I tried to remove the asbytes, and it seems to fix this error. Is it a bug in numpy?
答案 0 :(得分:23)
savetxt
以wb
模式打开文件,因此将所有内容写为字节。
如果我用“w”打开文件,我会收到第二个错误:
In [403]: x=np.ones((3,3),dtype=np.float64)
In [404]: with open('test.txt','w') as f:
np.savetxt(f,x,fmt='%.5f')
.....:
TypeError: must be str, not bytes
但
没有问题In [405]: with open('test.txt','wb') as f:
np.savetxt(f,x,fmt='%.5f')
.....:
In [406]: cat test.txt
1.00000 1.00000 1.00000
1.00000 1.00000 1.00000
1.00000 1.00000 1.00000
这是在Py3.4上;我的3.5 Python没有安装numpy
。但我不希望有任何区别。
确实
'%.5f'%1.2342
在您的系统上工作?你也可以试试
'%.5f %.5f %.5f'%tuple(mat[0,:])