AnsweredAssumed Answered

Unable to change data source path for group layer file

Question asked by jaygis on Jun 1, 2012
Latest reply on Mar 10, 2016 by astark@cob.org
Hi There,
I am having some difficulty changing the data source for a grooup layer. Below is the code that i am using. It processes LYR file successfully that has single data source but if LYR file has more than one data layers, it doesn't do it. Appreciate any feedback.

Thanks
Jay  



import arcpy, datetime, os, io, sys

try:

    #Read input parameters from GP dialog
   
 
    # Prod Setting...
    folderPath = arcpy.GetParameterAsText(0)
    output = arcpy.GetParameterAsText(1)
    sourceString = r"P:\Temp" #
    replacmentString = r"Z:\Temp" #
   
    #Create an output file
    outFile = open(output, "w")

    #Loop through each "LYR" file
    count = 0
    for path, dires, files in os.walk(folderPath):
        #for filename in os.listdir(folderPath):
        for filename in files:
            #fullpath = os.path.join(folderPath, filename)
            fullpath = os.path.join(path, filename)

            if os.path.isfile(fullpath):
                if filename.lower().endswith(".lyr"):
                    groupLayerName = ""
                    #Reference LYR
                    layerFile = arcpy.mapping.Layer(fullpath)

                    #Reference each layer in a layer file
                    count = 1
                    for lyr in arcpy.mapping.ListLayers(layerFile):
                        if lyr.isGroupLayer:
                            groupLayerName = lyr.name

                        if lyr.supports("DATASOURCE"):
                            dataSourceOrig = str(lyr.dataSource)
                            if dataSourceOrig.find(sourceString) >= 0:
                               
                                dataSourceNew = dataSourceOrig.replace(sourceString, replacmentString)

                                if groupLayerName:
                                    outFile.write(fullpath + "\t" + groupLayerName + "\t" +lyr.name + "\t"  + dataSourceOrig + "\t" + dataSourceNew + "\t" + "GROUP LAYER SOURCE" "\n")
                                    lyr.findAndReplaceWorkspacePath(sourceString, replacmentString, True)
                                    lyr.save()
                                else:
                                    outFile.write(fullpath + "\t" + "Non Group Layer" + "\t" + lyr.name + "\t" + dataSourceOrig + "\t" + dataSourceNew + "\t" + "SINGLE LAYER SOURCE" "\n")
                                    lyr.findAndReplaceWorkspacePath(sourceString, replacmentString, True)
                                    lyr.save()
                    del layerFile

    outFile.close()

    #Open the resulting text file
    os.startfile(output)

    #Delete variables that reference data on disk
    del outFile
   
except Exception, e:
  import traceback
  map(arcpy.AddError, traceback.format_exc().split("\n"))
  arcpy.AddError(str(e))

Outcomes