HOW TO

Write an ArcPy script to find maps throughout a folder tree and re-path layer data sources

Last Published: April 25, 2020

Summary

When data servers are upgraded or replaced, maps with layers that reference data on those systems may need to be updated to refer to data on a different system. The following is an example of a script to replace data sources of raster layers in maps residing in many different subfolders.

As an example, suppose the data sources for all color images were located in:

<drive>:<folder tree>/images/color


Suppose the raster data sources for all black-and-white images were in:
<drive>:<folder tree>/images


The sample script accepts two parameters: the root folder under which there are various subfolders containing maps, and the new path to the image files (all the way down to the /images subfolder).
Note:
If this example does not match the file organization in the prevailing environment, the functions illustrated may be helpful in developing a custom workflow.

Procedure


Code:
import arcpy, os

MapMainFolder = arcpy.GetParameterAsText(0) # topmost folder of maps to be updated
NewDataPath = arcpy.GetParameterAsText(1) # folder to which the raster data sources have been moved

for (root, dirs, files) in os.walk (MapMainFolder):
for fileName in files:
if os.path.splitext (fileName)[1] == ".mxd":
arcpy.AddMessage (fileName)
fullPath = os.path.join (root, fileName)
mxd = arcpy.mapping.MapDocument (fullPath)
rasterLayersUpdated = 0
for layer in arcpy.mapping.ListLayers (mxd): # list all layers in all dataframes
if layer.isRasterLayer:
if layer.supports ("SERVICEPROPERTIES"):
if layers.serviceProperties ['ServiceType'] == "ImageServer":
pass # don't try to re-path an online basemap
dataSrc = layer.dataSource
Color = 0
dataRoot = os.path.dirname (dataSrc)
if dataRoot.find ("Color") > 0:
newPath = os.path.join (NewDataPath, "Color")
else: # B&W
newPath = NewDataPath
layer.replaceDataSource (newPath, "RASTER_WORKSPACE", os.path.basename (dataSrc))
rasterLayersUpdated += 1
if rasterLayersUpdated > 0:
mxd.save()


The following screenshot shows the Parameters page of a toolbox script object for this Python script.
[O-Image]

Article ID:000011837

Software:
  • ArcMap

Receive notifications and find solutions for new or common issues

Get summarized answers and video solutions from our new AI chatbot.

Download the Esri Support App

Related Information

Discover more on this topic

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options