HOW TO
Instructions provided describe how to select a feature by attribute, select all the features that share a boundary with it, and then export the values of all of the features to a text file.
To complete this procedure using Python requires the use of the SearchCursor method to iterate through the values of the field.
Code:
# Import Modules...
import arcgisscripting, os, sys, string
# Create the Geoprocessor and set overwrites...
gp = arcgisscripting.create()
gp.OverwriteOutput = 1
# Set Variables...
gp.Workspace = r"D:\627514" # this is the folder that contains the data
input = "testdata.shp" # the zip code shapefile
lyr = "test_layer" # the name of the Make Feature Layer output
Code:
# Process: Make Feature Layer...
gp.MakeFeatureLayer_management(input, lyr)
Code:
# Create the Text File to write the zip values to...
outFile = open(r"D:\627514\zipcode.txt", "w")
Note:
If the text file does not already exist Python creates it.
Code:
# Build the Search Cursor...
fcSearch = gp.SearchCursor(lyr, "", "", "ZIP")
fc = fcSearch.Next()
Code:
while fc:
exp = "ZIP" + "='" + str(fc.getvalue("ZIP"))+"'"
# Process: Select by Attribute...
gp.SelectLayerbyAttribute_management(lyr, "NEW_SELECTION", exp)
# Process: Select by Location...
gp.SelectLayerbyLocation_management(lyr, "BOUNDARY_TOUCHES", lyr, "", "NEW_SELECTION")
Code:
# Build another Search Cursor to grab the zip values out of lyr...
txtSearch = gp.SearchCursor(lyr, "", "", "ZIP")
txtS = txtSearch.Next()
outFile.write("Zip Code: " + str(fc.getvalue("ZIP"))+ "\n")
while txtS:
zval = str(txtS.getvalue("ZIP"))
outFile.write(zval + "\n")
txtS = txtSearch.Next()
fc = fcSearch.Next()
Code:
outFile.close() # this closes the text file
del gp, input, lyr, fcSearch, fc, exp, outFile, zval, txtS, txtSearch
Article ID:000009943
Get help from ArcGIS experts
Download the Esri Support App