Useful code snippets - Python scripting in ArcGIS

Discussion created by jonesgeorge on Dec 5, 2014

Replace data source for multiple layer files that resides in folder

Important: There might be group layers so we have to check them while replacing the data source


Situation: you have to replace the datasource of all the layers in the folder C:\Trial\layers


Initial datasource: C:\trial\sample\*********

after running script: D:\GIS\trial\**********


The area represented by the '*' above shows they are same content


import arcpy import glob  layers = glob.glob(r"C:\Trial\layers\*.lyr") for lyr in layers:     l = arcpy.mapping.Layer(lyr)     for layer_inside in arcpy.mapping.ListLayers(l):           #checking whether it's a group layer or not         if layer_inside.isGroupLayer == False:              group =             print "old: "+str(layer_inside.dataSource)                #This will replace C:\trial\sample to D:\GIS\trial.             layer_inside.findAndReplaceWorkspacePath(r"C:\trial\sample","D:\GIS\trial")             print "new: "+str(layer_inside.dataSource)      #Saving the layer files with dataset name     arcpy.SaveToLayerFile_management(l, r"C:\Trial\layers2\\"+str(l.datasetName)+".lyr")   


I will be updating soon with more code snippets!!




- Jones