numpy.savetxt在python 3.5中导致格式不匹配错误 [英] numpy.savetxt resulting a formatting mismatch error in python 3.5

查看:1558
本文介绍了numpy.savetxt在python 3.5中导致格式不匹配错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用numpy.savetxt把一个numpy矩阵(Nx3,float64)保存到一个txt文件中:

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

这条线在python 2.7中工作,但在python 3.5中,我得到以下错误:
$ b


TypeError:array dtype(' )
$ /
$ b说明符('%.5f%.5f%.5f')
$ b 当我进入savetxt代码,打印错误(traceback.format_exc())在catch块(numpy.lib.npyio,第1158行)中,错误是完全不同的:


TypeError:write()参数必须是str,而不是字节

例外情况如下:
$ b $ pre $ f $($)

我试图删除asbytes,而且似乎解决了这个错误要么。这是一个在Numpy的错误?

解决方案

savetxt 打开 模式,因此写入所有的字节。



如果我用'w'打开文件,我得到第二个错误:在$ {

  [404]:用open('test.txt','w')作为f:
np.savetxt(f,x,fmt ='%。5f')
.....:
TypeError:必须是str,而不是字节

但是没有问题

$ [

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' ,x,fmt ='%5f')
.....:
在[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 ,:])


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

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

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:

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

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

解决方案

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

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

But there's no problem with

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

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

Does

'%.5f'%1.2342

work on your system? You could also try

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

这篇关于numpy.savetxt在python 3.5中导致格式不匹配错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆