numpy.savetxt 在 python 3.5 中导致格式不匹配错误

numpy.savetxt resulting a formatting mismatch error in python 3.5

我正在尝试使用 numpy.savetxt 将 numpy 矩阵(Nx3、float64)保存到 txt 文件中:

np.savetxt(f, mat, fmt='%.5f', delimiter=' ')

此行在 python 2.7 中有效,但在 python 3.5 中,我收到以下错误:

TypeError: Mismatch between array dtype ('float64') and format specifier ('%.5f %.5f %.5f')

当我进入 savetxt 代码时,在 catch 块(numpy.lib.npyio,第 1158 行)中打印错误(traceback.format_exc()),错误完全不同:

TypeError: write() argument must be str, not bytes

导致异常的代码行如下:

fh.write(asbytes(format % tuple(row) + newline))

我试图删除 asbytes,它似乎修复了这个错误。这是numpy中的错误吗?

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,:])