Reputation: 40718
How can I save NumPy arrays as part of a larger text file? I can write the arrays to a temp file using savetxt
, and then read them back into a string, but this seems like redundant and inefficient coding (some of the arrays will be large). For example:
from numpy import *
a=reshape(arange(12),(3,4))
b=reshape(arange(30),(6,5))
with open ('d.txt','w') as fh:
fh.write('Some text\n')
savetxt('tmp.txt', a, delimiter=',')
with open ("tmp.txt", "r") as th:
str=th.read()
fh.write(str)
fh.write('Some other text\n')
savetxt('tmp.txt', b, delimiter=',')
with open ("tmp.txt", "r") as th:
str=th.read()
fh.write(str)
Upvotes: 0
Views: 79
Reputation: 5138
First parameter of savetxt
fname : filename or file handle
So, you can open file in append mode and write to it:
with open ('d.txt','a') as fh:
fh.write('Some text\n')
savetxt(fh, a, delimiter=',')
fh.write('Some other text\n')
savetxt(fh, b, delimiter=',')
Upvotes: 2