Skip to content Skip to sidebar Skip to footer

How To Use Numpy.savetxt At The Top Of A File

My program writes several numpy arrays to a text file, then at the end I am trying to add the headers (another numpy array) to the top of the text file. I'm trying to either write

Solution 1:

You will need to write some padding space initially and then overwrite it later. There is no such operation as "insert content" in typical filesystems.

Then, to avoid savetxt() truncating your file, make it write to a StringIO object instead, which you can then copy into your file. Like this:

txt = StringIO.StringIO() # Python 3: io.BytesIO()
np.savetxt(txt, nparr, delimiter=',', fmt='%s')
Output.seek(0)
Output.write(txt.getvalue())

This assumes Output is a file object opened in a suitable mode.

Post a Comment for "How To Use Numpy.savetxt At The Top Of A File"