I am new to using Python scripts to execute ArcGIS tools. In my first script I am attempting to loop through many Select Layer by Location operations on overlapping feature classes. I want to create a new feature class that contains all of the "Block" features that have their center in the "Coverage" feature. All selecting polygon feature classes are in a "Coverage" feature dataset and all input feature classes are in a "Blocks" feature dataset. Both feature datasets are in a File Geodatabase. The selection completes with no unexepected behavior in a batch run of a functionally similar ModelBuilder Model, but the Python script below produces empty feature classes for the selected features.
My code is below:
#Import arcpy module
import os
import arcpy
from arcpy import env
#Define workspace
env.workspace = "C:\\ArcPrj\\NFHL_Data.gdb"
#Local variables
#Feature dataset containing blocks
Block_fd = "C:\\ArcPrj\\NFHL_Data.gdb\\CensusBlocks"
#Feature class containing coverage polygons
Coverage_fd = "C:\\ArcPrj\\NFHL_Data.gdb\\NFHLCoveragePolys"
#Output location
Output_fd = "C:\\ArcPrj\\NFHL_Data.gdb\\NFHLBLocks"
#Create lists from feature datasets to select from
env.workspace = Block_fd
blockList = arcpy.ListFeatureClasses()
env.workspace = Coverage_fd
coverageList = arcpy.ListFeatureClasses()
#Iterate through each feature class in the Block dataset and the Coverage
#dataset and perform operations
#Change workspace to main gdb
env.workspace = "C:\\ArcPrj\\NFHL_Data.gdb"
for i in range(len(blockList)):
#Change workspace to main gdb
env.workspace = "C:\\ArcPrj\\NFHL_Data.gdb"
#Select the ith feature class in the feature dataset
blocks = blockList[i]
coverage = coverageList[i]
#Make feature classes into feature layers
arcpy.MakeFeatureLayer_management(blocks, "blocks_lyr")
arcpy.MakeFeatureLayer_management(coverage, "coverage_lyr")
#Select blocks that have centroids in the coverage polygon
#(select layer by loc)
arcpy.SelectLayerByLocation_management("blocks_lyr", "HAVE_THEIR_CENTER_IN", "coverage_lyr", selection_type="NEW_SELECTION")
env.workspace = Output_fd
#Copy selection to a feature class
arcpy.CopyFeatures_management("blocks_lyr", blocks + "_NFHL")
#Clear previous layers
arcpy.Delete_management("blocks_lyr")
arcpy.Delete_management("coverage_lyr")
As a Python beginner I appreciate any help you can give me. Thank you.
Best Answer
The "Blocks" features and "Coverage" features were not indexed alphabetically as anticipated. Thus the iteration selected feature classes that did not overlap as expected. Adding
blockList.sort()
andcoverageList.sort()
after defining each list made sure that the correct feature classes were selected in the for loop.