numpy.savetxt resulting a formatting mismatch error in python 3.5

时间:2016-02-12 21:54:37

标签: numpy formatting python-3.5

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?

1 个答案:

答案 0 :(得分:23)

savetxtwb模式打开文件,因此将所有内容写为字节。

如果我用“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,:])