0

In General

I have to access and modify a specific property, e.g. data source, of one specific layer with arcpy. I know the name of the mxd-file, the dataframe and the layer. How can I access, for modification, this one single layer directly without the common for layer in arcpy.mapping.ListLayers(...) loop as suggested in other answers (e.g. in the manual or in case 18433)? I also don't manage to use UpdateLayer: this command allocates properties by fetching them from another layer, however, I don't have another layer which could deliver the desired properties.

Example

import arcpy, os
workspace_mxd = r"L:\project\home"
workspace_old = r"L:\project\scenario1"
workspace_new = r"L:\project\scenario2"
mxdfile = os.path.join(workspace_mxd,'mxd','map.mxd')
datasource = os.path.join(workspace_old,'data','points.shp')
layername = 'village'
arcpy.env.workspace = workspace_mxd
arcpy.env.overwriteOutput=True
mxd = arcpy.mapping.MapDocument(mxdfile)
df = arcpy.mapping.ListDataFrames(mxd)
for dataframe in df:
    for lyr in arcpy.mapping.ListLayers(mxd, layername, dataframe):
        lyrDatasource = lyr.dataSource if lyr.supports('dataSource') else 'N/A'
        if lyrDatasource == datasource:
            lyr.findAndReplaceWorkspacePath(workspace_old,workspace_new,False)
mxd.save()
del mxd

By this approach, the property data source is modified for one specific layer. The approach looks inflated for this purpose. E.g. the two for loops are, in the specific case, for one dataframe and one layer only. Isn't there a shortcut to do what is finally done with lyr.findAndReplaceWorkspacePath(workspace_old,workspace_new,False)?

2
  • 1
    Please include a code snippet that illustrates precisely what you have tried instead of just alluding to your attempts.
    – PolyGeo
    Apr 20, 2021 at 19:45
  • If you know how to iterate a layer list, you know how to isolate a layer.
    – Vince
    Apr 21, 2021 at 3:31

1 Answer 1

1

When iterating over the layers in your loop, check layer.name for a match to the target layer name, and\or use the filter parameter in ListLayers to reduce the list to layers matching your target layer name. If adding a filter to ListLayers, you can operate on the first layer returned if you are confident there is only one possible match.

Your Answer

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

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