Writing a Grid ASCII File

1. Introduction

You may have had times when you wondered if the tools in a GIS application were working correctly. If you've developed your own tools you may have wondered how to test them to see if they work just as you intend. Python can be used to create "synthetic" data that has known, exact, values.

2. Writing a Synthetic ASCII File

The code below will write out an ASCII grid file with a gradient from the upper left to the lower right. Run this code and then open the file in ArcGIS and you'll see a big, gray, raster. The problem is that ArcGIS requires a histogram (information on the contents of the raster) to properly display the raster. Go into "Properties" for the layer, select the "Symbology" tab and select "Custom" for the "Stretch Type". When you click "OK" you should see the raster data that you created. You can also use the information tool to query the individual pixels values in the raster.

TheFile.write("ncols 10\n")
TheFile.write("nrows 10\n")
TheFile.write("xllcorner     0.0\n")
TheFile.write("yllcorner     0.0\n")
TheFile.write("cellsize      1.0\n")
TheFile.write("NODATA_value  -9999\n")
# use the code from 3.4 to write out 10 rows and 10 columns of data here

You can use this approach to create an infinite variety of rasters. They can even contain randomized data to test spatial analysis features and simulate natural phenomenon. You can also create "pixel art" (see the Web for ideas).

Note: ASCII Grid files typically end in an "asc" extension for "ASCII". Newer versions of ArcGIS also recognize the "grd" extension as an ASCII Grid file. I recommend sticking with the "asc" extension for backward compatibility.

3. Hidden File Extensions

MS-Windows now hides file extensions of "known" file types. This means that if you write out the file above, you'll see the "asc" file extension after the file because Windows does not know about the ASCII GRID file type. However, if you write out a "txt" file, Windows will hide the extension. Then, if you rename the file to "asc", the file will look like it is named "gradient.asc" but it will actually be named "gradient.asc.txt"!

Important: We highly recommend MS-Windows users go into the "Folder Options" settings dialog (available in any folder view on Windows 7 and 8 under "Organize-> Folder and search options") and uncheck the setting for "Hide extensions for known file types" in the "View" tab.

Additional Resources

Wikipedia: ESRI Grid Formats

ESRI Documentation: ArcInfo ASCII Grid Format

© Copyright 2018 HSU - All rights reserved.