Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

EDIT: I am using Python3.4

like image 535
tooty44 Avatar asked Jul 09 '14 17:07

tooty44


People also ask

How do you write a NumPy array into a csv file?

You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.

How do I write an array in CSV?

We can write an array to a CSV file by first converting it to a DataFrame and then providing the CSV file's path as the path argument using the Dataframe. to_csv() method. Since the default value of the sep argument is , , we have to provide the DataFrame and the path argument to the Dataframe. to_csv() method.

How do I write a NumPy array to a file in Python?

Let us see how to save a numpy array to a text file. Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function.

How do I export a NumPy array to excel?

Numpy has a “savetxt” method which saves numpy array to csv file. Use “savetxt” method of numpy to save numpy array to csv file.


1 Answers

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=",")

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

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=",")
like image 107
unutbu Avatar answered Oct 15 '22 10:10

unutbu