I am trying my hand at python for the first time. Using 2.7.18 Idle to check for errors (b/c I don't understand visual studio yet) I am wanting to go through all MXDs in a folder, find the layer Backup (shapefile) and change its source to a different folder and a GDB with another name, then update the TOC layer name. I don't get errors, but the script does not do anything. All my printed statements print but nothing seems to be working. Any suggestions for this newbie?
import arcpy
from arcpy import env
# Set the workspace for the folder containing MXDs
arcpy.env.workspace = r"S:\Workgroups\Test"
mxdList = arcpy.ListFiles("*.mxd")
# Iterate through all MXDs in the workspace
for mxd in mxdList:
mxdpath = env.workspace + "\\" + mxd
print (mxd + "Is being processed")
mxdNext = arcpy.mapping.MapDocument(mxdpath)
for df in arcpy.mapping.ListDataFrames(mxdNext,"Layers"):
for lyr in arcpy.mapping.ListLayers(mxd, "Backup", df):
if lyr == "Backup":
Lyr.replaceDataSource(r"S:\Workgroups", "SHAPEFILE_WORKSPACE", "Backup.shp",
r"S:\Workgroups\Data.gdb\Final", "FILEGDB_WROKSPACE")
if lyr.name == "Backup":
lyr.name = "Final"
print("lyr.name")
arcpy.RefreshTOC()
del mxd
print("Data sources updated for all MXDs.")
@Tom_Laue I went back and indented the df and a few other tweaks. I got it to work now! Thanks to @RhettZufelt @AlfredBaldenweck as well! Hope I got everyone.
Awesome 🎉
Don't get too frustrated as it gets easier the more you use Arcpy.
The more code you write, the more you can "steal" ideas from your other scripts, or ESRI samples or GIS Stack Exchange, etc.
Even ChatGPT sometimes can produce usable Esri Python code!