Tuesday, August 30, 2011

Python code to create an ASCII file from arrays

Suppose you have the Numpy arrays X, Y and Z - which can contain strings, floats, integers etc - and you want to create an ASCII file in which each column corresponds to the elements of these arrays. The code snippet below allows you to do that.

In the example below, tmp.dat corresponds to the output file and X (strings), Y (floats) and Z (floats) are the arrays you want to export.

 file=open('tmp.dat','w') #create file  
 for x,y,z in zip(X,Y,Z):  
      file.write('%s\t%f\t%f\n'%(x,y,z))     #assume you separate columns by tabs  
 file.close()     #close file  

Be sure to modify the %s and %f if you change the array data types.

Thanks to Tyrel Johnson for the trick.

1 comment:

  1. probably a faster way to do that whould be to avoid the for loop

    import numpy as np

    a = ['a', 'b', 'c']
    b = [1, 2, 3]

    c = np.array([a,b]).T
    np.savetxt('output_file', c, fmt='%s')

    ReplyDelete