简体   繁体   English

如何将numpy数组写入csv文件?

[英]How to write a numpy array to a csv file?

I want to open up a new text file and then save the numpy array to the file. 我想打开一个新的文本文件,然后将numpy数组保存到该文件中。 I wrote this bit of code: 我写了这段代码:

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

It appears you are using Python3. 看来你正在使用Python3。 Therefore, open the file in binary mode ( wb ), not text mode ( w ): 因此,以二进制模式( 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. 另外,关闭文件句柄abc ,以确保所有内容都写入磁盘。 You can do that by using a with -statement (as shown above). 您可以使用with -statement (如上所示)来实现。

As DSM points out, usually when you use np.savetxt you will not want to write anything else to the file, since doing so could interfere with using np.loadtxt later. 正如DSM所指出的那样,通常在使用np.savetxt您不希望在文件中写入任何其他内容,因为这样做可能会影响以后使用np.loadtxt 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 : 因此,不是使用文件句柄,而是简单地将文件名作为第一个参数传递给np.savetxt可能更容易:

import numpy as np
foo = np.array([1,2,3])
np.savetxt('file_2', foo, delimiter=",")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM