Skip to main content
edited tags
Link
Midavalo
  • 29.9k
  • 11
  • 51
  • 105
Source Link

Having trouble replaceDataSource loop in Python

In ArcGIS (using 10.4) I have my layout set up, shapefile A symbolized and labeled. What I need to do is print this layout to pdf, then change the source of shapefile A to the next in a series of several hundred, have it look the same, change the title, and print the pdf. I'm trying to loop through each shapefile in a folder. The shapefiles are polygon. The legend stays the same because each shapefile has the same number of polygons, symbolized the same way. The labels should stay the same, but move as the polygons they label change shape and position. The extent is constant. This is easy to do interactively in ArcGIS: go into the Layer Properties, Source tab, Set Data Source... In trying to do this in Python, I'm having difficulty. My code maybe isn't looping. It prints one map. I think the replaceDataSource {dataset_name} needs to be a variable (the ""), but I can't figure how to do that.

>>> import arcpy  
... import os  
... mxd = arcpy.mapping.MapDocument("CURRENT")   
... df = arcpy.mapping.ListDataFrames(mxd, "*")[0]    
... lyr = arcpy.mapping.ListLayers(mxd, "*", df)[3]             
... output_dir = r"\\path\PDFs"   
... arcpy.env.workspace = r"\\path\Set1Test"
... shapelist = arcpy.ListFeatureClasses()       
... for shape in shapelist:                      
...     lyr.replaceDataSource(r"\\path\Set1Test", "SHAPEFILE_WORKSPACE", "")
...     TextElement = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "MapTitleText")[0]  
...     TextElement.text = lyr.datasetName                                     
...     arcpy.mapping.ExportToPDF(mxd, r"\\path\PDFs\Map " + lyr.datasetName)

I've also tried this, with the same result:

>>> import arcpy
... import os
... mxd = arcpy.mapping.MapDocument("CURRENT")
... df = arcpy.mapping.ListDataFrames(mxd, "*")[0]
... lyr = arcpy.mapping.ListLayers(mxd, "*", df)[3]
... output_dir = r"\\path\PDFs"
... for file in os.listdir(r"\\path\Set1\Set1Test"):
...     if file.startswith ("Set"):
...             lyr.replaceDataSource(r"\\path\Set1\Set1Test", "SHAPEFILE_WORKSPACE", "")
... TextElement = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "MapTitleText")[0]
... TextElement.text = lyr.datasetName 
... arcpy.mapping.ExportToPDF(mxd, r"\\path\PDFs\Map " + lyr.datasetName)