1

I have a 2D numpy array. I want to make a ASCII file out of it. Here's the code I am using where a3 is the numpy array

f = open('ASCIIout.asc', 'w')
numpy.savetxt(ASCIIout, a3)
f.write("ncols " + str(ncols) + "\n")
f.write("nrows " + str(nrows) + "\n")
f.write("xllcorner " + str(xllcorner) + "\n")
f.write("yllcorner " + str(yllcorner) + "\n")
f.write("cellsize " + str(cellsize) + "\n")
f.write("NODATA_value " + str(noDATA) + "\n")
f.close()

Now I open it with append option and write the 2D array values:

f_handle = open(ASCIIout, 'a')
numpy.savetxt(f_handle, MyArray, fmt="%.3f")
f_handle.close()

However, I have a couple problems. First, the fmt really does not work I get values like this:

9.999000000000000000e+03 

If I JUST use the code below line of code, I get -9999.000 1.345, but then, I haven't attached ncols, nrows, etc to the ASCII file.

numpy.savetxt(f_handle, MyArray, fmt="%.3f")

My data range from 0 to 6. What I really want to get is:

-9999 1.345 -9999 3.21 0.13 -9999

where I do NOT get decimals after -9999 and I do get decimals after real data such as 1.345 I made the ASCII file in R, I am wondering there should be a easy way to do it in Python. Thanks for your help in advance.

3
  • 1
    In the first code block, what does numpy.savetxt(ASCIIout, a3) do? You haven't told us what's in ASCIIout (is it just the string "ASCIIout.asc"?), and you haven't told us what's in a3. Commented Jul 22, 2014 at 2:33
  • 1
    why dont you use the header option to numpy.savetxt Commented Jul 22, 2014 at 4:56
  • @frank128791 a3 is the numpy aray and ASCIIout is just the name of the file I am going to write on. Commented Jul 22, 2014 at 14:54

1 Answer 1

2

If your intention is to have the "stop value" -9999 appear without the decimal point, you can let savetxt() save all the values with the "%.3f" format, and replace the one result you don't want with the one you want:

from StringIO import StringIO
import numpy as np
f = StringIO()
x = np.array(( -9999, 1.345, -9999, 3.21, 0.13, -9999), dtype=float)
np.savetxt(f, x, fmt='%.3f')
f.seek(0)
fs = f.read().replace('-9999.000', '-9999', -1)
f.close()
f = open('ASCIIout.asc', 'w')
f.write("ncols " + str(ncols) + "\n")
f.write("nrows " + str(nrows) + "\n")
f.write("xllcorner " + str(xllcorner) + "\n")
f.write("yllcorner " + str(yllcorner) + "\n")
f.write("cellsize " + str(cellsize) + "\n")
f.write("NODATA_value " + str(noDATA) + "\n")
f.write(fs)
f.close()

If you want all the integer values represented without decimals, .replace('.000', '', -1) would accomplish that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.