Writing an array to a text file

I am trying to write a 5x3 array to a text file following the example found here using this code.

import numpy as np
data = np.loadtxt('array_float.txt')
with open('out.txt', 'w') as outfile:
    for data_slice in data:
        np.savetxt(outfile, data_slice, fmt='%4.1f')

      

This results in the following error:

File C:\Python34\lib\site-packages\numpy\lib\npyio.py", line 1087, in savetxt
  fh.write(asbytes(format % tuple(row) + newline))
TypeError: must be str, not bytes

      

The savetxt doesn't seem to like the outfile object. I can get savetxt to work when I provide the actual filename. For example, this works:

np.savetxt('out.txt', data_slice, fmt='%4.1f')

      

But only the last line of the array gets saved to 'out.txt'.

+3


source to share


2 answers


You have to open the file in binary mode (using ab

or wb

)



import numpy as np
data = np.loadtxt('array_float.txt')
with open('out.txt', 'ab') as outfile:
    for data_slice in data:
        np.savetxt(outfile, data_slice, fmt='%4.1f')

      

+2


source


I suggest you use the Python pickle module. This allows any array to be stored with very few complications or lines of code.

Try the following:



import pickle
f = open(name_of_file,'w')
pickle.dump(f,name_of_array)
f.close()

      

0


source







All Articles