writing arrays to binary file
Travis E. Oliphant
oliphant.travis at ieee.org
Wed Jan 25 05:02:48 EST 2006
Sheldon wrote:
> Hi everyone,
>
> I have a short program the writes the output data to an acsii file:
>
> import sys
> import os
> import string
> import gisdata
> from Numeric import *
>
> def latlon(area_id, i, j):
> lon_file = "lon_%s.dat" % area_id
> flon = open(lon_file, 'wa')
> lat_file = "lat_%s.dat" % area_id
> flat = open(lat_file, 'wa')
> for x in range(i):
> for y in range(j):
> flat.write("%f\n" % gisdata.xy2lonlat(area_id,x,y)[1])
> flon.write("%f\n" % gisdata.xy2lonlat(area_id,x,y)[0])
> flat.close()
> flon.close()
> #------------------------------------------------------------
> if __name__ == '__main__':
> tile_info ={"ibla_35n13e":[1215,1215],
> "ibla_46n16e":[1215,1215],
> "ibla_57n40w":[1215,1215],
> }
> for t in tile_info.keys():
> xsize = tile_info[t][0]
> ysize = tile_info[t][1]
> result = latlon_(t, xsize, ysize)
> Now this works but the output is in ascii form. Whenever I try to write
> it binary form by creating the 2D array and then opening the file with
> open("filename", 'wb'), I lose the decimals that are vital. The input
> data is float with about 4 decimal places.
You need to use the tostring() method and write that out in binary form.
flon = open(lon_file,'wb')
flon.write(your2darray.tostring())
of course you will need to manage byte-order issues if you will be
transferring this file to a different kind of processor.
Alternatively, with new NumPy there is a tofile method that you can use
to write in either ascii or binary form.
-Travis Oliphant
More information about the Python-list
mailing list