How to write a numpy array to a csv file? How to write a numpy array to a csv file? numpy numpy

How to write a numpy array to a csv file?


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

import numpy as npfoo = 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 npfoo = np.array([1,2,3])np.savetxt('file_2', foo, delimiter=",")