1

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
2

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
  • It worked, thanks. Now, i want to do something more complex, as you can se bellow. Can you help me please? – raphael May 11 '17 at 12:12
3

You just need to change your indents to only save if the element is changed.

#find the element, and change it
                if elm.name == "logo":
                    elm.sourceImage = r"C:\logo\newlogo.jpg"
                    print fullpath
                    mxd.save()
  • I tryed to do that, and got errors that i dont remember.. maybe i did something wrong... i'm going to test it again. – raphael May 10 '17 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.