Arcpy - Select by location - iterate through gdb feature class and export to new fc

1001
2
04-05-2020 08:06 PM
BrianMcNamara2
New Contributor II

Hi, I am trying to use arcpy to run a select by location and export the resulting selection (intersect) as a new feature class. I have set my workspace to the gdb containing the featureclasses I want to select by, and the features I want to select are a tile index feature class called 'tile_index'. The code will run but doesn't have any output. Any help would be great.

Thanks!

# Import arcpy and set path to data
import arcpy
arcpy.env.workspace = r"C:\folder\Data.gdb\"


# Get the list of the featureclasses to process
fc_tables = arcpy.ListFeatureClasses()

for fc in fc_tables:
   arcpy.SelectLayerByLocation_management('fc', 'intersect', 'tile_index') 
   arcpy.CopyFeatures_management(fc_tables, r"C:\Data.gdb\%Name%_selection")‍‍‍‍‍‍‍‍‍‍‍‍
Tags (2)
0 Kudos
2 Replies
JohannesBierer
Occasional Contributor III

Don't know if I'm up to date but I think you have to use make feature layer infront of your select by location. Out of the help files:

import arcpy
arcpy.env.workspace = "c:/data/mexico.gdb"
# Make a layer and select cities which overlap the chihuahua polygon
arcpy.MakeFeatureLayer_management('cities', 'cities_lyr') 
arcpy.SelectLayerByLocation_management('cities_lyr', 'intersect', 'chihuahua')

you should use:

arcpy.env.workspace = r"C:\folder\Data.gdb" and not
arcpy.env.workspace = r"C:\folder\Data.gdb\"

r"C:\Data.gdb\%Name%_selection" will not work in python code, 
you will need to create a unique name for your output file.

0 Kudos
Ian-Horn
New Contributor II

I'm trying to do something similar, but instead of writing selected features to a layer, I want to deleted the selected features.

arcpy.env.workspace = r'K:/3DBasemaps/3DBasemaps/scratch_raw_points.gdb'


# list feature classes in the workspace

treeFeatureClasses = arcpy.ListFeatureClasses("", 'Point')

print(treeFeatureClasses)


for fc in treeFeatureClasses:

    buildingPts = r'K:/3DBasemaps/3DBasemaps/scratch.gdb/' + fc

    print(buildingPts)

    arcpy.management.SelectLayerByLocation(fc,'ARE_IDENTICAL_TO', buildingPts)

    print(fc + " County points were selected againts " + buildingPts + " points")

    arcpy.management.DeleteFeatures(fc)

    print(buildingPts + fc + "points deleted from " + fc)

 

But instead of deleting the selected features, it deletes all the features.  

0 Kudos