python - 使用文件处理程序时 numpy savetxt 失败

标签 python arrays numpy

在 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/

相关文章:

javascript - 使用 gen_validatorv4.js 通过 Internet Explorer 验证数组中的项目

python - 确定特定的有序向量是否在列表/数组中

python - 在滑动窗口中应用 np.where

python - 使用 numpy.take 进行更快的花式索引

java - 多操作系统下Tomcat webapps文件路径

c - 如何将每个数字扫描到数组槽中?

python - 我应该使用什么索引将 numpy 数组转换为 pandas 数据框?

python - 用 Python 替换字符串的子字符串

python - 如何加快我的 Python 扑克手与手牌赢率计算器

Python - 过滤/排序大文件的建议?