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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值