1

I would like to use numpy.savetxt to write a numpy array, with the option of writing either to stdout, or as part of a file (by redirecting stdout). e.g. (in Python3)

import numpy as np
import sys

def output( a ):
    print( 'before np.savetxt' )
    np.savetxt( sys.stdout.buffer, a  )
    print( 'after np.savetxt' )

a = np.array( [ ( 1, 2, 3 ), ( 4, 5, 6 ) ] )

output( a )

with open( 'test', 'w' ) as file_out:
    sys.stdout = file_out
    output( a )

This writes (to stdout):

before np.savetxt
1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00
4.000000000000000000e+00 5.000000000000000000e+00 6.000000000000000000e+00
after np.savetxt

but the 'test' file contains these entries out of order:

> cat test
1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00
4.000000000000000000e+00 5.000000000000000000e+00 6.000000000000000000e+00
before np.savetxt
after np.savetxt

Is it possible to have these outputs in consistent order, or should I use a different approach to combine numpy.savetxt with other commands to write to the same file?

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
bmorgan
  • 525
  • 5
  • 8
  • 2
    Just add `flush=True` to the first `print` to make sure it flushes to the underlying buffer beforehand, or call `sys.stdout.flush()`. – Eryk Sun Apr 13 '14 at 10:34
  • You can also just [disable all buffering](https://stackoverflow.com/a/181654/6055997) on stdout. – Matt Kramer Feb 01 '20 at 03:56

1 Answers1

2

You can use inside your output() function only the savetxt command, passing the header and footer arguments:

def output( a ):
    header = 'before np.savetxt'
    footer = 'after np.savetxt'
    np.savetxt(sys.stdout.buffer, a, header=header, footer=footer)

As well reminded by @DavidParks, it should be sys.stdout for Python 2.7 and sys.stdout.buffer for Python 3.x.

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234