我想打开一个新的文本文件,然后将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=",")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句