I am currently updating a script we use at work. The script was designed to loop through the layers in an mxd and go through and replace the data sources so that when someone opened up the final setup mxd the symbology would be applied. An example of how this should work is below.
All the script does is return an empty mxd. If I remove lines 54 to 68 the mxd is copied along with all the broken layers including the layer called "study Areas". What am I doing wrong with the lyr.replaceDataSource?
# --- Check out Spatial Analyst --------------------------------------------------------------------------
arcpy.CheckOutExtension("Spatial")
arcpy.env.overwriteOutput = True
# studyAreaSize = Study area buffer size (metres) (String)
studyAreaSize = 1000
# siteName = Site name (String)
siteName = "TheStreet"
# projectNumber = Project number (String)
projectNumber = "1234"
# GISFolder = Location of GIS folder (Folder)
GISFolder = r"D:\Projects\1234\GIS"
#geodatabase = location of geodatabase
geodatabase = r"D:\Projects\1234\GIS\Databases\Test.gdb"
# dataFrom = Where should the data come from? Salisbury, Sheffield, Kent, Edinburgh - Value List
dataFrom = "Salisbury"
#create Study Area
arcpy.Buffer_analysis(r"D:\Projects\1234\GIS\SHP\Site\Site.shp", "D:/Projects/1234/GIS/Databases/Test.gdb/StudyArea", studyAreaSize,"","","ALL")
#locate previous project data
if dataFrom == "Salisbury":
mappingFolder = r"X:/GIS/Data/WA Mapping/SHP"
else:
mappingFolder = "R:/GIS/WA Mapping/SHP"
studyAreas = os.path.join(mappingFolder, "WA_Project_Study_Areas.shp")
arcpy.MakeFeatureLayer_management(studyAreas, "WA_studyAreas")
# --- Extract previous projects data
arcpy.SelectLayerByLocation_management("WA_studyAreas", "INTERSECT", "D:/Projects/1234/GIS/Databases/Test.gdb/StudyArea", "1000")
featuresCount = arcpy.GetCount_management("WA_studyAreas")
if str(featuresCount) == "0":
arcpy.AddMessage("No WA study areas in the vicinity")
else:
arcpy.conversion.FeatureClassToGeodatabase("WA_studyAreas", geodatabase)
# --- Copy the template MXD
arcpy.SetProgressorLabel("Copying the template MXD")
# --- Template source ---------
if dataFrom == "Salisbury":
srcMXD = "X:/GIS/_Templates/Heritage.mxd"
# Create mxd destination path
dstMXDName = projectNumber + "_" + siteName + "_Setup.mxd"
dstMXD = os.path.join(GISFolder, "MXD", dstMXDName)
shutil.copy(srcMXD, dstMXD)
mxd = arcpy.mapping.MapDocument(dstMXD)
# Get data frame for removing and updating layers
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
# Loop through layers - remove or fix sources
for lyr in arcpy.mapping.ListLayers(mxd):
# Check WA Project Data
if lyr.name == "Historic England Listed Buildings":
if lyr.supports("DATASOURCE"):
if lyr.dataSource = r"X:\GIS\_Templates\TemplateMasters\Heritage_Template.gdb\HE_StudyArea":
lyr.replaceDataSource(geodatabase, "FILEGDB_WORKSPACE", studyAreaPrefix + "_StudyArea")
else:
arcpy.mapping.RemoveLayer(df, lyr)
# Save the MXD
mxd.save()