python3-numpy: Appending to a file using numpy savetxt

Meenakshi picture Meenakshi · Jan 5, 2015 · Viewed 57.7k times · Source

I am trying to append data to a file using numpy's savetxt function. Below is the minimum working example

#!/usr/bin/env python3
import numpy as np
f=open('asd.dat','a')
for iind in range(4):
    a=np.random.rand(10,10)
    np.savetxt(f,a)
f.close()

The error that I got is something about the type of the error

File "/usr/lib/python3/dist-packages/numpy/lib/npyio.py", line 1073, in savetxt fh.write(asbytes(format % tuple(row) + newline)) TypeError: must be str, not bytes

This error doesn't occur in python2 so I am wondering what the issue could be. Can anyone help me out?

Answer

user4352571 picture user4352571 · Jan 16, 2015

You should open file by binary mode.

#!/usr/bin/env python3
import numpy as np        
f=open('asd.dat','ab')
for iind in range(4):
    a=np.random.rand(10,10)
    np.savetxt(f,a)
f.close()

reference: python - How to write a numpy array to a csv file? - Stack Overflow How to write a numpy array to a csv file?