在 Windows 7 上,使用最新的 numpy 1.13.3 和 PYTHON 3.5,如果我有一个名为 points 的数组,形状为 m x 6,dtype 为 float32。我可以将数组保存到“foo.txt”文件,如下所示:
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 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() argument must be str, not bytes
During handling of the above exception, another exception occurred:
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\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: Mismatch between array dtype ('float32') and format specifier ('%f %f %f %d %d %d')
我错过了什么吗?
最佳答案
此行为仅发生在 Python 3 中,并且取决于 numpy 的版本。
对于旧版本的 numpy(1.14.0 之前),文件必须以 wb
模式打开以使用 savetxt
写入字节。
在 numpy 1.14.0 或更高版本中,此问题已解决。问题中的示例按预期工作。
关于python - 使用文件处理程序时 numpy savetxt 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47273840/