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