如何写一个numpy的阵列到CSV文件? [英] How to write a numpy array to a csv file?

查看:1101
本文介绍了如何写一个numpy的阵列到CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打开一个新的文本文件,然后保存numpy的阵列到文件中。我写此位code的:

I want to open up a new text file and then save the numpy array to the file. 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?

此外,我发现所谓file_2终端创建了一个空文件,但没有什么是写在里面。

Additionally, I found an empty file created in the terminal called file_2, but nothing is written inside it.

编辑:我使用Python3.4

I am using Python3.4

推荐答案

看样子你正在使用Python3。因此,以二进制方式打开文件( WB ),而不是文本模式(是W

It appears you are using Python3. Therefore, open the file in binary mode (wb), not text mode (w):

import numpy as np
foo = np.array([1,2,3])
with open('file'+'_2', 'wb') as abc:
    np.savetxt(abc, foo, delimiter=",")

另外,关闭文件句柄, ABC ,以确保一切都写入磁盘。为此,您可以通过使用 语句来(如上图所示)。

Also, close the filehandle, abc, to ensure everything is written to disk. You can do that by using a with-statement (as shown above).

由于DSM所指出的,通常当你使用 np.savetxt 你不想写什么别的文件,因为这样做可能会使用<$ C干扰$ C> np.loadtxt 之后。因此,而不是使用一个文件句柄,可能会更容易简单地将文件作为第一个参数的名称传递给 np.savetxt

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. 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:

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

这篇关于如何写一个numpy的阵列到CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆