0

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) 

1 Answer 1

2

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=',') 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.