ERROR
When attempting to add a layer file to a map using the addLayer() method in ArcGIS Pro, an error similar to the following occurs:
ValueError: C:\path\to\layer_file\.lyrx

Example Code Triggering the Error
aprx = arcpy.mp.ArcGISProject("CURRENT")
m = aprx.listMaps("Map")[0]
m.addLayer(r"C:\path\to\layer file\.lyrx") #Fails with ValueError
The error occurs because the Map.addLayer() method strictly requires either:
Passing a raw file path, “C:\path\to\file.lyrx", for example, directly to addLayer is unsupported and raises a ValueError.
Convert the layer file path to a LayerFile object before calling addLayer:
lf = arcpy.mp.LayerFile(r"C:\path\to\file.lyrx ")
aprx = arcpy.mp.ArcGISProject("CURRENT")
m = aprx.listMaps("Map")[0]
m.addLayer(lf) #Successfully adds the layer to the map.
import arcpy
# Load the current project and reference the map
aprx = arcpy.mp.ArcGISProject("CURRENT") # Use "CURRENT" for active project
map_obj = aprx.listMaps("Map")[0] # Replace "Map" with your map name
# Convert layer file path to a LayerFile object
lyrx_path = r"C:\path\to\your\layerFile.lyrx" # Update with your path
lyrx_file = arcpy.mp.LayerFile(lyrx_path)
# Add to map
map_obj.addLayer(lyrx_file)
print("Layer added successfully!")
For more information about working with layers and maps in ArcGIS Pro, refer to the documentation in the Related Information section.
Article ID: 000036079
Get help from ArcGIS experts
Start chatting now