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