0

I have a script to replace the data source on layer files in an mxd based on a geodatabase input from the user and a feature class with a matching name to the layer. This script works as intended as long as the layers are not grouped. The final product needs to have the layers arranged in group layers by year, and all years in a single group layer (ie, All data>Years>Layers). Once I put the layers into group the script no longer works.

Is there a way to have to script read the nested layers, or add the layers to groups after the script has run?

import arcpy, os

mxd = arcpy.mapping.MapDocument('current')
df = arcpy.mapping.ListDataFrames(mxd)[0]
workDir=workDir=arcpy.GetParameterAsText(0)
workSpaceType = "FILEGDB_WORKSPACE"
for lyr in arcpy.mapping.ListLayers(mxd):
    datasource=lyr.name
    lyr.replaceDataSource(workDir, workSpaceType, datasource)

   
arcpy.RefreshTOC()
arcpy.RefreshActiveView() 
 

The script returns the following error

Traceback (most recent call last): File "W:\wlap\nan\Workarea\sjohnst\datasource.py", line 9, in lyr.replaceDataSource(workDir, workSpaceType, datasource) File "e:\sw_nt\arcgis\desktop10.8\arcpy\arcpy\utils.py", line 182, in fn_ return fn(*args, **kw) File "e:\sw_nt\arcgis\desktop10.8\arcpy\arcpy_mapping.py", line 686, in replaceDataSource return convertArcObjectToPythonObject(self._arc_object.replaceDataSource(*gp_fixargs((workspace_path, workspace_type, dataset_name, validate), True))) ValueError: Layer: Unexpected error

1 Answer 1

0

Check if the layer supports a datasource before doing the replace. ListLayers returns the all the layer (group layer and sub layers). You can also skip the actual group layer, which doesn't have a data source to update.

import arcpy

mxd = arcpy.mapping.MapDocument('current')
df = arcpy.mapping.ListDataFrames(mxd)[0]
workDir = workDir=arcpy.GetParameterAsText(0)
workSpaceType = "FILEGDB_WORKSPACE"
for lyr in arcpy.mapping.ListLayers(mxd):
    # Skip Grouplayers
    if not lyr.isGroupLayer:
        # Only try and update layers that have a datasource
        if lyr.supports("DATASOURCE"):
            datasource=lyr.name
            lyr.replaceDataSource(workDir, workSpaceType, datasource)

arcpy.RefreshTOC()
arcpy.RefreshActiveView() 

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.