[GIS] Find and Replace data source script

arcgis-10.1arcpymxdpython

The following script is supposed to find and replace all shapefiles in a mxd (that exist in the folder) to the new SDE data source. No errors when running the script however, when I open the MXD in ArcGIS 10.1SP1 nothing changed. Any suggestions what is wrong?

import arcpy, os, glob

#find all the MXD's in the directory tree
for root, subFolders, files in os.walk(r"C:\Users\lmuhammad\Documents\ArcGIS\SearchandReplace\Testing"):
for filename in files:
    fullpath = os.path.join(root, filename)
    basename, extension = os.path.splitext(fullpath)
    if extension.lower() == ".mxd":
        print "------------------------------"
        print filename
        #open the map document
        MXD = arcpy.mapping.MapDocument(fullpath)
        #get all the layers
        for lyr in arcpy.mapping.ListLayers(MXD):
            #get the source from the layer
            if lyr.supports("datasource"):
                source = r"R:\Shapefiles\Road_Casings\RoadCasing.shp"
                print "%s -> %s" % (lyr, source)
                basename, extension = os.path.splitext(source)
                if extension.lower() == ".sde":
                    #This is the NEW SOURCE that you want to point to
                    datapath = r"Database Connections\Connection to GISD.sde\GISDEV.TRANSPORTATION\GISDEV.PAVEMENTEDGE"
                    #replace the old path wih the new
                    lyr.findAndReplaceDatasource(source, datapath, "NEWROAD", False)
        #save your changes
        MXD.saveACopy(r"C:\Users\lmuhammad\Documents\ArcGIS\SearchandReplace\Testing\test2.mxd")
        del MXD

Best Answer

I would recommend breaking this up into two functions:

  1. A function to replace the data sources in one MXD
  2. A function that calls the previous function on each MXD in a directory tree

You'll want to test the first function thoroughly by itself before moving on to the second.

I recommend using a Python IDE such as PyScripter to develop, test and debug your scripts.

Please try to work at this yourself and if you run into a wall, edit your question to include the pertinent information such as what you tried (including code!), what you expected to happen, and what error messages or unexpected output you got.

Related Question