How do I change the data source of all layers in a map document using ArcPy and Python?
The documentation entitled Updating and fixing data sources with arcpy.mapping has several examples:
There are numerous reasons why data sources need to be repaired or redirected to different locations. The idea of making these changes manually in every affected map document can be overwhelming. Methods are available with the arcpy.mapping scripting environment that make it possible to automate these changes without even having to open a map document. You have control of updating data sources for individual layers, or you can update all layers at once that have a common workspace.
The common reasons I have come across to do this are broken data sources, and switching from a DBMS service (accessing SDE as an admin user) to Operating System Authentication (through a default SDE, so regular users can access the layers in an MXD).
Both cases, running through many MXDs with arcpy would prevent TONS of manual labor. Something like this might be helpful for either case:
#input is a list of mxds, after parsing folders for mxd in mxd_list: mxd_read = arcpy.mapping.MapDocument(mxd) #following will allow repairing source from DBMS to OSA if lyr.supports("SERVICEPROPERTIES"): service_properties = lyr.serviceProperties authent = service_properties.get('AuthenticationMode', 'N/A') if authent == 'DBMS': lyr.findAndReplaceWorkspacePath(find_workspace_path=lyr.dataSource, replace_workspace_path=r"C:\ThisIsTheNew\SDE_ConnectionFile.sde") lyr.save #Now go through any broken data sources and repair list_src = arcpy.mapping.ListBrokenDataSources(mxd_read) for lyr in list_src: lyr.replaceDataSource([new workspace/database], [database type], [new dataset name]) lyr.save mxd_read.save()
These are the main two that I've used, but if all you want to do is replace layer data sources (whether they're broken or not, or whatever the source database type is), you can use the layer.replaceDataSource() method after mapping the MXD.