Select to view content in your preferred language

Select By Attribute with Variable

1449
3
05-02-2021 02:46 PM
ebrown
by
New Contributor

I'm trying to iterate through a shapefile with all of the roads in the State of Maine, select only the roads in towns relevant to my project, and then create one new feature class with just those roads. I'm working in Python in a Jupyter notebook and I'm a beginner in both Python and ArcGIS. This code runs, but selects all of the roads, not just those in the town list.

 

# Create town list
town_list = ['Bangor','Hampden','Veazie','Orono','Brewer','Old Town']

arcpy.env.overwriteOutput = True
for town in town_list:
    select = """TOWN = '{}'""".format(town)
    arcpy.SelectLayerByAttribute_management(ME_roads,'NEW_SELECTION',select)
    arcpy.CopyFeatures_management(ME_roads,relevant_roads)

 

0 Kudos
3 Replies
DavidPike
MVP Frequent Contributor

I'd say there's a few too many quotes in select:

select = "TOWN = '{}'".format(town)

Have you also made it a feature layer to run it on? 

DanPatterson
MVP Esteemed Contributor

Of course you could always just use

Split By Attributes (Analysis)—ArcGIS Pro | Documentation


... sort of retired...
0 Kudos
JoeBorgione
MVP Emeritus

From another set of eyes; I like f strings over the format() function if you are using Python 3.x:

select = f'TOWN = {town}'

 

I too wondered what @DavidPike mentioned about a feature layer...

 

That should just about do it....
0 Kudos