My python script should identify sections of roads based on two criteria: wheather they're adjacent to roads with a lower speed limit, and weather they're shorter than 400m. I get an error related to the MakeFeatureLayer tool. Any help is appreciated.
My code:
import arcpy
# Set up workspace and input feature class
arcpy.env.workspace = r"C:\Users\Local.gdb"
input_fc = "Full_Roads_CC"
# Set up a search cursor to iterate over the features in the feature class
fields = ["Limit_TRO","Shape_Length", "SHAPE@"]
cursor = arcpy.da.SearchCursor(input_fc, fields)
# Initialize some variables to track the state of the search
prev_speed = None
prev_line = None
selected_lines = []
# Loop thourgh the features in the fc
for row in cursor:
speed = row[0]
length = row[1]
line = row[2]
# Check if the current line is between two sections of lines where speed = 20
if prev_speed == 20 and speed == 30 and length < 400:
selected_lines.append(line)
# Update the previous speed and line
prev_speed = speed
prev_line = line
# Select the roads that meet the criteria
output_layer = "selected_roads"
where_clause = "Speed = 30 AND Shape_Length < 400"
arcpy.management.MakeFeatureLayer(input_fc, output_layer,where_clause)
# Add the selected roads to the output layer
arcpy.management.CopyFeatures(selected_lines, output_layer)
The error is:
ExecuteError Traceback (most recent call last)
In [7]:
Line 28: arcpy.management.MakeFeatureLayer(input_fc, output_layer,where_clause)
File C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\management.py, in MakeFeatureLayer:
Line 9395: raise e
File C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\management.py, in MakeFeatureLayer:
Line 9392: retval = convertArcObjectToPythonObject(gp.MakeFeatureLayer_management(*gp_fixargs((in_features, out_layer, where_clause, workspace, field_info), True)))
File C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\geoprocessing\_base.py, in <lambda>:
Line 512: return lambda *args: val(*gp_fixargs(args, True))
ExecuteError: ERROR 000358: Invalid expression
Failed to execute (MakeFeatureLayer).
I get that error if r"C:\Users\Local.gdb\Full_Roads_CC" doesn't have a field named "Speed".
R_
The expression looks ok. The only thing I can think of is your field type, if Speed is a string rather than float/number then the expression would fail in this manner.
if it is a string and you don't need to do any > < comparison:
where_clause = "Speed = '30' AND Shape_Length < 400"