Monday, 17 September 2018

arcpy - How to save just some mxds through 'if' in python?


I have a simple code, that changes a picture in the layout, based on the element name. It works fine, for all MXDs in the same folder of the script.


The problem is, the script saves every single .mxd file int the folder, not just the ones it actually changed the picture i wanted.



How can i make it to save just the ones it actually changes?


import arcpy, os

inputPath = os.curdir

#Loop through each MXD file
for filename in os.listdir(inputPath):
fullpath = os.path.join(inputPath, filename)
if os.path.isfile(fullpath):
if filename.lower().endswith(".mxd"):


mxd = arcpy.mapping.MapDocument(fullpath)
for elm in arcpy.mapping.ListLayoutElements(mxd, "PICTURE_ELEMENT"):
#find the element, and change it
if elm.name == "logo":
elm.sourceImage = r"C:\logo\newlogo.jpg"
print fullpath
mxd.save()
del mxd

Answer




Check that your indentation is consistent and correct. To only save the mxd where it has changed, put the mxd.save() into the if. This means that if it hasn't got an Element named logo then it won't change it and it won't save it.


I would also use .lower() on the filename and the elm.name just in case the name is not lower case (python is case dependant).


#Loop through each MXD file
for filename in os.listdir(inputPath):
fullpath = os.path.join(inputPath, filename)
if os.path.isfile(fullpath) and filename.lower().endswith(".mxd"):
mxd = arcpy.mapping.MapDocument(fullpath)
for elm in arcpy.mapping.ListLayoutElements(mxd, "PICTURE_ELEMENT"):
# find the element, and change it
if elm.name.lower() == "logo":

elm.sourceImage = r"C:\logo\newlogo.jpg"
print fullpath
mxd.save()
del mxd

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...