1

I'm trying to build a script that uses select by attribute and select by location to do some operations on a couple of shapefiles containing a large amount of points and polygons. Preferably, I want to make it runnable without adding any files to Arcmap, but I can´t get Select by Attribute to work and I don´t understand why. Here´s an example:

arcpy.env.workspace = "C:/Projekt\Mitt_skolval/Test_adresser_skolor/"
fcs = arcpy.ListFeatureClasses()

print(fcs)

returns

[u'Adresser_18dec2020.shp', u'Skolskjutsomraden_4_5_2021.shp', u'Skolskjutsomraden_6_2021.shp', u'Skolskjutsomraden_7_9_2021.shp', u'Skolskjutsomraden_F_3_2021.shp']

If I then try this:

adresser = fcs[0]

arcpy.SelectLayerByAttribute_management(adresser, "NEW_SELECTION", "FID = 3")

It throws this error:

Runtime error  Traceback (most recent call last):   File "<string>", line 9, in <module>   File "c:\program files (x86)\arcgis\desktop10.8\arcpy\arcpy\management.py", line 7759, in SelectLayerByAttribute     raise e ExecuteError: The value cannot be a feature class ERROR 000840: The value is not a Raster Layer. ERROR 000840: The value is not a Mosaic Layer.

Saying from what I understand that I can´t use Select by attribute on a shapefile, which is weird. HOWEVER, if I add the same shapefile to the ToC and run

arcpy.SelectLayerByAttribute_management(Adresser_18dec2020, "NEW_SELECTION", "FID = 3")

It works.

Why is this?

I know I can solve this by creating feature layers, but I want to avoid this if possible.

1 Answer 1

4

A selection cannot be made directly on a feature class or shapefile. It must be made on a feature layer. The ToC contains layers created when data is added to the map document, that is why you can do a selection on them.

Your script will need to include MakeFeatureLayer_management to perform the way you want. You can include your selection in the where_clause of the tool.

1
  • Thank you. I figured that might be the case, although I had the feeling I´d done this before. I guess not!
    – Emanuelv
    Jan 20, 2021 at 8:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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