The problem is that you haven't flushed f. "2\n" is still in the file buffer and overwrites the other data after cat completes when f is eventually closed. But there Is a better way to do this. Reading the numpy docs savetxt, you can pass in a file handle. Numpy can use the existing file handle to write its data. No need for a second temporary file.
import numpy as np
with open(file1, "w") as f:
f.write('2\n')
np.savetxt(f, datafile, fmt)