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

2022-01-12 00:00:00 numpy python-3.5 formatting

问题描述

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

I'm trying to save a numpy matrix (Nx3, float64) into a txt file using numpy.savetxt:

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

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

This line worked in python 2.7, but in python 3.5, I'm getting the following error:

TypeError: 数组 dtype ('float64') 和格式不匹配说明符('%.5f %.5f %.5f')

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

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

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() 参数必须是 str,而不是字节

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

导致异常的代码行如下:

The line of code resulting the exception is the following:

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

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

I tried to remove the asbytes, and it seems to fix this error. Is it a bug in numpy?


解决方案

savetxtwb 模式打开文件,从而将所有内容写入字节.

savetxt opens the file in wb mode, and thus writes everything as bytes.

如果我用w"打开文件,我会收到第二个错误:

If instead I open the file with 'w', I get your second error:

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.但我不希望有什么不同.

This is on Py3.4; I don't have numpy installed with my 3.5 Python. But I wouldn't expect a difference.

'%.5f'%1.2342

在您的系统上工作?你也可以试试

work on your system? You could also try

'%.5f %.5f %.5f'%tuple(mat[0,:])

相关文章