arcpy open shapefile as layer from file path

96 views Asked by At

I am using arcpy in arcgis pro 2.9. I got a python toolbox built that has a input for a shapefile layer, it works if user has loaded that shapefile into map and select it from drop down in the parameter list. But is there a way to just open that shapefile from file path directly? I've searched for quite a while, didn't find anything to do that.

At this point, that python toolbox would use arcpy.GetParameter(0) to get that layer object, I would really need a way to just get that layer object from shapefile path, e.g. C:\test\data\myshapefile.shp

1

There are 1 answers

0
TeeB24 On

I believe that the solution is to use arcpy.MakeFeatureLayer_management and arcpy.mapping.Layer See example below - I can't test at the moment, but worth a try.

# Create a feature layer from shapefile on disk
shapefile_path = r"C:\test\data\myshapefile.shp"
feature_layer_name = "my_feature_layer"
arcpy.MakeFeatureLayer_management(shapefile_path, feature_layer_name)

# Get the layer object
layer_object = arcpy.mapping.Layer(feature_layer_name)