This is my first attempt to code in Python.

I have one polygon layer, A, that covers the UK and another set/group of layers that each cover sections of the UK, B. I want to select by location features of A contained entirely within B. As B is split into lots of separate sections (due to its size) I need to do this in a loop.

So far I have this code which I adapted from a similar question of Automating Select by Location in ArcGIS Desktop?:

# Import system modules
import sys, string, os, arcgisscripting, arcpy

# Create the Geoprocessor object
gp = arcgisscripting.create()

mxd = arcpy.mapping.MapDocument("CURRENT")
df = mxd.activeDataFrame
groupName = "WBBS_waterways"

# Load required toolboxes...
gp.AddToolbox("c:/program files (x86)/arcgis/desktop10.3/ArcToolbox/Toolboxes/Data Management Tools.tbx")

# Script arguments...
A = "//FILES/UNIXHome/Git/waterbirds_project/data/OS_waterways.shp"
outfolder ="//FILES/UNIXHome/Git/waterbirds_project/data/" 

basename = "OS_just_rivers"

allLayers = arcpy.mapping.ListLayers(mxd, groupName, df)[0]

for layer in(allLayers):
        # Process: Select Layer By Location...
        gp.SelectLayerByLocation_management(A, "COMPLETELY_WITHIN", D, "", "NEW_SELECTION")
        outname = outfolder + "\\" + basename + D
        #Process: Copy Features...
        gp.CopyFeatures_management(A, outname, "", "0", "0", "0") 

And this is the error message I get:

Runtime error  Traceback (most recent call last):   File "<string>", line 28, in <module> ExecuteError: ERROR 000368: Invalid input data.  

which I think means something is going wrong on this line: gp.SelectLayerByLocation_management(A, "COMPLETELY_WITHIN", D, "", "NEW_SELECTION"), it looks like python can't find layer D but I'm not sure how to make it recognise layer D.


A is a feature class (think what you see in ArcCatalog). You can't perform a selection on a feature class. You need to create a layer (think what you see in the ArcMap table of contents, with symbology and other unique aspects) from your feature class before you can apply a selection to it.

fc = = r"//FILES/UNIXHome/Git/waterbirds_project/data/OS_waterways.shp"

arcpy.MakeFeatureLayer_management (fc, "lyr")
arcpy.SelectLayerByLocation_management ("lyr", "COMPLETELY_WITHIN", D, "", "NEW_SELECTION")
  • Thanks! That works. I don't really understand why though. The OS_waterways is already a shape file and was already in my ArcMap table of contents. I don't really understand why I needed to add it to the ArcMap table of contents again. – Jennifer Taylor Sep 29 '17 at 8:46
  • 1
    Because you're referencing the feature class (via the file path), not the layer in the table of contents. – Emil Brundage Sep 29 '17 at 16:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.