我想打开一个新的文本文件,然后将 numpy 数组保存到文件中。我写了这段代码:
foo = np.array([1,2,3])
abc = open('file'+'_2', 'w')
np.savetxt(abc, foo, delimiter=",")
我收到这个错误:
TypeError Traceback (most recent call last)
<ipython-input-33-fea41927952b> in <module>()
2 model = cool
3 abc = open('file'+'_2', 'w')
----> 4 np.savetxt(abc, foo, delimiter=",")
/usr/local/lib/python3.4/site-packages/numpy/lib/npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments)
1071 else:
1072 for row in X:
-> 1073 fh.write(asbytes(format % tuple(row) + newline))
1074 if len(footer) > 0:
1075 footer = footer.replace('\n', '\n' + comments)
TypeError: must be str, not bytes
有人知道怎么回事吗?
此外,我发现在终端中创建了一个名为 file_2 的空文件,但其中没有任何内容。
编辑:我正在使用 Python3.4
最佳答案
看来您正在使用 Python3。因此,以二进制模式(wb
)而不是文本模式(w
)打开文件:
import numpy as np
foo = np.array([1,2,3])
with open('file'+'_2', 'wb') as abc:
np.savetxt(abc, foo, delimiter=",")
此外,关闭文件句柄 abc
,以确保所有内容都已写入磁盘。您可以使用 with
-statement 来做到这一点(如上图)
正如 DSM 指出的那样,通常当您使用 np.savetxt
时,您不想向文件写入任何其他内容,因为这样做可能会干扰使用 np.loadtxt
稍后。因此,与其使用文件句柄,不如将文件名作为第一个参数传递给 np.savetxt
可能更容易:
import numpy as np
foo = np.array([1,2,3])
np.savetxt('file_2', foo, delimiter=",")
关于python - 如何将 numpy 数组写入 csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24659814/