Writing a Grid ASCII File
In Review
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=open("C:/gradient.asc","w") 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") TheFormat="{0} " for i in range(0,10): for j in range(0,10): TheFile.write(TheFormat.format(i+j)) TheFile.write("\n") TheFile.close()
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.
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 namd "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