Search code examples
pythonarcpywing-ide

Having some issues using selecting layer by location syntax


My instructions:

Create a Python script that selects parcels from "coa_parcels.shp" that intersect with the shapefile "floodplains.shp" and creates a new shapefile that only contains the selected parcels.

The location of the workspace and the three shapefiles (coa_parcels, floodplains, and the output) should be treated as user-defined inputs using "raw_input" statements.

Below is example pseudocode for the script for this part:

  • Begin
  • Get user input for the workspace
  • Get user input for the input feature class name (e.g. coa_parcels.shp)
  • Get user input for the select feature class name (e.g. floodplains.shp)
  • Get user input for an output feature class name (e.g. selected_parcels.shp)
  • Set the workspace and overwrite output settings
  • Create a temporary feature layer
  • Select from layer by location based on the select feature class
  • Copy the selected features to a new feature class
  • Print a message letting the user know that a new feature class was created
  • End

My script:

import arcpy

workSpace = raw_input("What is the workspace location? ")
inFeature = raw_input("What is the input feature class name? ")
selFeature = raw_input("What is the select feature class name? ")
outFeature = raw_input("What is the output feature class name? ")

arcpy.env.workspace = workSpace
arcpy.env.overwriteOutput = True
arcpy.MakeFeatureLayer_management("coa_parcels.shp", "lyr") 
arcpy.SelectLayerByLocation_management(coa_parcels.shp,"INTERSECT",floodplains.shp, "NEW_SELECTION")
arcpy.CopyFeatures_management("lyr", "selected_parcels")
print "A new feature class",outFeature,"has been created!"here

My error is this : NameError: name 'coa_parcels' is not defined


Solution

  • Look closely at the line which is throwing the error:

    arcpy.SelectLayerByLocation_management(coa_parcels.shp,
    

    By not including the layer name in quotes, you're indicating to Python that it should use a variable coa_parcels as the parameter input to the select layer by location tool.


    Unsolicited, and unrelated to your error, the Make Feature Layer tool doesn't create shapefiles. Nothing prevents you from including .shp in a layer name (clearly, since that isn't where your error arises!) but for "best practices" I would recommend naming layers more distinctly so you don't accidentally try to pass a layer to a tool which would only accept a shapefile.