4

How do I change the data source of all layers in a map document using ArcPy and Python?

  • 2
    If you clarified your question to include the real-life problem that you are trying to solve, you might get some answers with code examples in them... – DavidF Dec 1 '10 at 18:14
  • did you manage to fix that ? – Smalis May 7 '15 at 17:33
9

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.

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy