使用文件处理程序时,numpy savetxt失败 [英] numpy savetxt fails when using file handler

查看:419
本文介绍了使用文件处理程序时,numpy savetxt失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows 7上,使用最新的numpy 1.13.3和PYTHON 3.5,如果我有一个名为points的数组,其形状为m x 6,dtype为float32。我可以将数组保存为以下 foo.txt文件:

On windows 7, with the newest numpy 1.13.3 and PYTHON 3.5, if I have an array called points, with shape m x 6 and dtype of float32. I can save the array to a "foo.txt" file as below:

np.savetxt('foo.txt', points, fmt='%f %f %f %d %d %d')

但是我运行

with open('foo.txt', 'w') as f:
    np.savetxt(f, points, fmt='%f %f %f %d %d %d')

我收到以下错误:


TypeError跟踪(最近一次调用最近)
〜\AppData\Local\Continuum \anaconda3\lib\site-packages\numpy\lib\npyio.py
在savetxt中(fname,X,fmt,定界符,换行符,标头,页脚,
注释)1214尝试:
-> 1215 fh.write(asbytes(格式%元组(行)+换行符))1216除了TypeError:

TypeError Traceback (most recent call last) ~\AppData\Local\Continuum\Anaconda3\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments) 1214 try: -> 1215 fh.write(asbytes(format % tuple(row) + newline)) 1216 except TypeError:

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

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

在处理上述异常期间,发生了另一个异常:

During handling of the above exception, another exception occurred:

TypeError Traceback( ()1中的最近一次呼叫last),
open('foo.txt','w')为f:
----> 2 np。 savetxt(f,points,fmt ='%f%f%f%f%d%d%d')3

TypeError Traceback (most recent call last) in () 1 with open('foo.txt', 'w') as f: ----> 2 np.savetxt(f, points, fmt='%f %f %f %d %d %d') 3

〜\AppData\Local\Continuum\ txtanaconda3\lib\site-packages\numpy\lib\npyio.py
在savetxt中(fname,X,fmt,定界符,换行符,标头,页脚,
注释)1217提高TypeError(数组dtype('%s')
与 1218格式说明符('%s')之间的不匹配
-> 1219%(str(X.dtype),format))1220如果len(footer)> 0:1221 footer = footer.replace('\n','\n'+注释)

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments) 1217 raise TypeError("Mismatch between array dtype ('%s') and " 1218 "format specifier ('%s')" -> 1219 % (str(X.dtype), format)) 1220 if len(footer) > 0: 1221 footer = footer.replace('\n', '\n' + comments)

TypeError:数组dtype之间不匹配('float32')并格式化
说明符('%f%f%f%d%d%d')

TypeError: Mismatch between array dtype ('float32') and format specifier ('%f %f %f %d %d %d')

我是否遗漏了任何东西?

Am I missing anything?

推荐答案

此行为仅在Python 3上发生,并且取决于numpy的版本。

This behaviour only happens with Python 3, and depends on the version of numpy.

对于numpy的较早版本(1.14.0之前的版本),必须使用 wb 模式打开文件,以写入 savetxt

With older versions of numpy (before 1.14.0) the file must be opened with wb mode to write bytes with savetxt.

使用numpy 1.14.0或更高版本,可以解决此问题。问题中的示例按预期方式工作。

With numpy 1.14.0 or later, this issue is resolved. The example in the question works as expected.

这篇关于使用文件处理程序时,numpy savetxt失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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