I'm using numpy savetxt()
to save the elements of a matrix to file as a single row (I need to print lots of them in order). This is the method I've found:
import numpy as np
mat = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
with open('myfile.dat','a') as handle:
np.savetxt(handle, mat.reshape(1,mat.size), fmt='%+.8e')
handle.close()
There are 2 questions:
1) Is savetxt()
the best option? I need to print 1e5 to 1e7 of these things... and I don't want i/o bottlenecking the actual computation. I'm guessing reopening the file each iteration is a bad plan, speed-wise.
2) Ideally I would have some context data printed to start each row so my output might look like:
(N foo mat):
...
6 -2.309 +1.000 +2.000 ...
7 -4.273 +1.000 +2.000 ...
8 -3.664 +1.000 +2.000 ...
...
I could do this using np.append()
, but then the first number won't print as an INT. Is this sort of thing doable directly in savetxt()
? Or do I need a C-like fprintf()
anyways?