1

Continually to Changing part of text element using ArcPy? ,when i use this code in order to delete text element (the words "Land Use"):

import arcpy
from arcpy import env 

env.workspace = r"G:\desktop\Project"
for mxdname in arcpy.ListFiles("*.mxd"):
    print mxdname
    mxd = arcpy.mapping.MapDocument(r"G:\desktop\Project\\" + mxdname)
    for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
        elm.text = elm.text.replace('Land Use', '') 
        print 'done'
    mxd.save()   
del mxd

enter image description here

i get this result:

>>> 
Project.mxd
done
done
done
>>>  

enter image description here

The code delete the words "Land Use", but i don't understand:

  1. Why it printed three times the word "done", while i wanted to print it just one time, after it finished?
  2. Why the other words in the title "for residence" didn't jump to the top like that: enter image description here
5

'Done' is printed in each iteration, whether 'Land Use' applies or not. So if there are three text elements, then 'done' will be printed three times. To just have it show once, you have to remove it from the for loop and show it after the for loop. In other words, your print statement should not be indented:

env.workspace = r"G:\desktop\Project"
for mxdname in arcpy.ListFiles("*.mxd"):
    print mxdname
    mxd = arcpy.mapping.MapDocument(r"G:\desktop\Project\\" + mxdname)
    for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
        elm.text = elm.text.replace('Land Use', '')
    print 'done'
    mxd.save()
del mxd


EDIT: Just saw the second part of your question.

There might be an escape sequence forcing a linebreak (\n) in your code that you are not seeing.

After:

elm.text = elm.text.replace('Land Use', '')

You could try to add this as well:

elm.text = elm.text.replace('\n','')

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.