Write array to text file

11,306

Solution 1

You should 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')

Solution 2

I suggest you use Python's pickle module. It allows the saving of any array with very few complications or lines of code.

Try this:

import pickle
f = open(name_of_file,'w')
pickle.dump(f,name_of_array)
f.close()
Share:
11,306
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm trying to write a 5x3 array to a text file following an 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')
    

    It 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
    

    It seems savetxt doesn't like the outfile object. I'm able to get savetxt to work when I specify the actual outfile name. For example, this works:

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

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