Batch Replace a Layer within multiple MXDs in a Folder

This one is helpful if you have many MXDs located within a folder that need a layer replaced. For those who create Map Books, this could come handy.


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
# Name: Replace layers in MXD TOC
# Purpose: This script is meant to be added to an ArcGIS Toolbox.
#          It will copy all MXDs within the specified directory to a folder on your desktop.
#          Then it will scan each MXD in that desktop folder, looking for a layer name, per user input, 
#          and replace with an existing layer file, per user input.
# Author:   Nicole Ceranek
# Date Created: 02/11/2016
# Last Modified:    -
# ArcGIS Version    10.1
# Python Version:   2.7
#------------------------------------------------------------------------------------------------
## Import modules
import arceditor
import os, arcpy, datetime, sys,time, os.path, glob, logging, traceback
from arcpy import env, mapping
from datetime import date, timedelta, datetime
from time import ctime
from os import listdir
from os.path import isfile, join

## Set date time variables
datetime120 = time.strftime("%Y%m%d_%H%M%S")

arcpy.env.overwriteOutput = True

# Set start time
def hms_string(sec_elapsed):
    h = int(sec_elapsed / (60 * 60))
    m = int((sec_elapsed % (60 * 60)) / 60)
    s = sec_elapsed % 60.
    return "{}:{:>02}:{:>05.2f}".format(h, m, s)
start_time = time.time()

# Input
indir = arcpy.GetParameterAsText(0)
oldlyrname = arcpy.GetParameterAsText(1)
lyrfile = arcpy.GetParameterAsText(2)
newlyr = arcpy.mapping.Layer(lyrfile)

# Create output directories on user desktop
userhome = os.path.expanduser('~')
desktop = userhome+"/Desktop/"

outdir = desktop+"MXDcopy"
if not os.path.exists(outdir):
        os.makedirs(outdir)

removedir = outdir+"/MXDsWithReplacement"
if not os.path.exists(removedir):
        os.makedirs(removedir)
# Create output log file
LogFile = open(outdir+"/LayerReplacementLog_"+datetime120+".csv","w")

# Remove old layer from MXDs and save copy to removeddir
try:
    workspace = indir
    arcpy.env.workspace = workspace
    mxdList = arcpy.ListFiles("*.mxd")
    LogFile.write("Process,MXD,From-Old,To-New\n")
    for mapdoc in mxdList:
        filepath = os.path.join(workspace,mapdoc)
        mxd = arcpy.mapping.MapDocument(filepath)
        filename = mapdoc
        output = os.path.join(outdir,filename)
        arcpy.AddMessage("Copying MXD "+mapdoc)
        LogFile.write("Copying,"+mapdoc+","+indir+","+outdir+"\n")
        mxd.saveACopy(output)
        pass
except Exception, e:
  import traceback
  map(arcpy.AddError, traceback.format_exc().split("\n"))
  arcpy.AddError(str(e))

# Add new layer from MXDs and save copy to replaceddir
arcpy.env.overwriteOutput = True
try:
    workspace = outdir
    arcpy.env.workspace = workspace
    mxdList = arcpy.ListFiles("*.mxd")
    for mapdoc in mxdList:
        filepath = os.path.join(workspace,mapdoc)
        arcpy.AddMessage("Updating file: "+mapdoc)
        mxd = arcpy.mapping.MapDocument(filepath)
        filename = mapdoc
        output = os.path.join(removedir,filename)
        for df in arcpy.mapping.ListDataFrames(mxd):
            for lyr in arcpy.mapping.ListLayers(mxd,"",df):
                if lyr.name==oldlyrname:
                    arcpy.AddMessage("Replacing: "+str(lyr)+" with: "+str(newlyr))
                    LogFile.write("Replacing Layer,"+str(mapdoc)+","+str(lyr.name)+","+str(newlyr)+"\n")
                    arcpy.mapping.InsertLayer(df,lyr,newlyr,"BEFORE")
                    arcpy.mapping.RemoveLayer(df,lyr)
                    arcpy.RefreshActiveView()
                    arcpy.RefreshTOC()
                    mxd.saveACopy(output)
                else:
                    LogFile.write("Ignoring,"+mapdoc+","+str(lyr.name)+"\n")
                    pass
except Exception, e:
  import traceback
  map(arcpy.AddError, traceback.format_exc().split("\n"))
  arcpy.AddError(str(e))

# Set stop time
import time
import datetime
end_time = time.time()
#print "\nElapsed time: {}".format(hms_string(end_time-start_time))
LogFile.write("\nElapsed time: {}".format(hms_string(end_time-start_time))+",\n")
LogFile.close()
exit()

Comments

Popular posts from this blog

Updating GDB_Items XML Definitions

Animation with ArcGIS Pro

Add Field to a SQL Geodatabase using T-SQL