【发布时间】:2015-05-21 21:24:21
【问题描述】:
我正在尝试按照此处使用此代码找到的示例将 5x3 数组写入文本文件。
import numpy as np
data = np.loadtxt('array_float.txt')
with open('out.txt', 'w') as outfile:
for data_slice in data:
np.savetxt(outfile, data_slice, fmt='%4.1f')
这会导致以下错误:
File C:\Python34\lib\site-packages\numpy\lib\npyio.py", line 1087, in savetxt
fh.write(asbytes(format % tuple(row) + newline))
TypeError: must be str, not bytes
看来 savetxt 不喜欢 outfile 对象。当我指定实际的输出文件名时,我可以让 savetxt 工作。例如,这有效:
np.savetxt('out.txt', data_slice, fmt='%4.1f')
但只有数组的最后一行被保存到“out.txt”。
【问题讨论】:
标签: python python-3.x numpy