HOW TO
Instructions provided describe how to select a feature by an 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. This article is specific to using the ArcPy module installed with ArcGIS 10.x.
To complete this procedure using Python requires the use of the Search Cursor method to iterate through the values of the field.
Code:
# Import modules
import arcpy, os, sys, string
# Create envrionmental variables
arcpy.env.overwriteOutput = True
arcpy.env.workspace = r"D:\Data" # This is the folder that contains the data
# Set variables
input = "testdata.shp" # The zip code shapefile
lyr = "test_layer" # The name of the Make Feature Layer output
Code:
# Processes to make feature layer...
arcpy.MakeFeatureLayer_management(input, lyr)
Code:
# Create the text file to write the zip values to...
outFile = open(r"D:\Data\zipcodes.text", "w")
Code:
# Build search cursor for all 10.x...
fcSearch = arcpy.SearchCursor(lyr, "", "", "ZIP")
Code:
for fcRow in fcSearch:
# Create expression based on the current row's zip code value
exp = '"ZIP" = ' + "'" + str(fcRow.getValue("ZIP")) + "'"
# Process: Select Layer by Attribute...
arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", exp)
# Process: Select Layer by Location...
arcpy.SelectLayerByLocation_management(lyr, "BOUNDARY_TOUCHES", lyr, "", "NEW_SELECTION")
Code:
# Build another search cursor to grab the zip values out of lyr...
txtSearch = arcpy.SearchCursor(lyr, "", "", "ZIP")
outFile.write("Zip Code: " + str(fcRow.getValue("ZIP")) + "\n")
for txtRow in txtSearch:
zval = str(txtRow.getValue("ZIP"))
outFile.write(zval + "\n")
Code:
outFile.close() # This closes the text file
del input, lyr, fcRow, txtRow, txtSearch, fcSearch, outFile, zva
Code:
# Build data access search cursor for 10.1+
fcSearch = arcpy.da.SearchCursor(lyr, ["ZIP"])
for fcRow in fcSearch:
exp = '"ZIP" = ' + "'" + str(fcRow[0]) + "'"
# Process: Select Layer by Attribute...
arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", exp)
# Process: Select Layer by Location...
arcpy.SelectLayerByLocation_management(lyr, "BOUNDARY_TOUCHES", lyr, "", "NEW_SELECTION")
# Build another search cursor to grab the zip values out of lyr...
txtSearch = arcpy.da.SearchCursor(lyr, ["ZIP"])
outFile.write("Zip Code: " + str(fcRow[0]) + "\n")
for txtRow in txtSearch:
zval = str(txtRow[0])
outFile.write(zval + "\n")
outFile.close() # This closes the text file
del input, lyr, fcRow, txtRow, txtSearch, fcSearch, outFile, zval
Article ID:000011842
Get help from ArcGIS experts
Download the Esri Support App