Python 如何将 numpy 数组写入 csv 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24659814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write a numpy array to a csv file?
提问by tooty44
I want to open up a new text file and then save the numpy array to the file. I wrote this bit of code:
我想打开一个新的文本文件,然后将 numpy 数组保存到文件中。我写了这么一段代码:
foo = np.array([1,2,3])
abc = open('file'+'_2', 'w')
np.savetxt(abc, foo, delimiter=",")
I get this error:
我收到此错误:
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
Does anyone know whats wrong?
有谁知道出了什么问题?
Additionally, I found an empty file created in the terminal called file_2, but nothing is written inside it.
此外,我发现在终端中创建了一个名为 file_2 的空文件,但其中没有写入任何内容。
EDIT: I am using Python3.4
编辑:我正在使用 Python3.4
采纳答案by unutbu
It appears you are using Python3. Therefore, open the file in binary mode (wb), not text mode (w):
看来您正在使用 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=",")
Also, close the filehandle, abc, to ensure everything is written to disk. You can do that by using a with-statement(as shown above).
此外,关闭文件句柄 ,abc以确保所有内容都写入磁盘。您可以通过使用 -with语句(如上所示)来做到这一点。
As DSM points out, usually when you use np.savetxtyou will not want to write anything else to the file, since doing so could interfere with using np.loadtxtlater. So instead of using a filehandle, it may be easier to simply pass the name of the file as the first argument to np.savetxt:
正如 DSM 指出的那样,通常在您使用时,np.savetxt您不会想在文件中写入任何其他内容,因为这样做可能会干扰np.loadtxt以后的使用。因此,与其使用文件句柄,不如简单地将文件名作为第一个参数传递给np.savetxt:
import numpy as np
foo = np.array([1,2,3])
np.savetxt('file_2', foo, delimiter=",")

