Select to view content in your preferred language

Move Layer

09-08-2017 02:42 PM
Regular Contributor

I am trying to move TOC layers with the following python code, seems simple enough. Basically i am trying to move TaxParcels1 layer above the Sections layer of my current mxd  but i am not sure why i keep getting the error is it because my layers start with an upper case? Also do i have to save to a new mxd for the layer move to happen?

import arcpy

mxd = arcpy.mapping.MapDocument(r"C:\Temp\Split MXD.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
for lyr in arcpy.mapping.ListLayers(mxd, "", df):
    if == "Taxparcels1":
        moveLayer = lyr
    if == "Sections":
        refLayer = lyr
arcpy.mapping.MoveLayer(df, refLayer, moveLayer, "BEFORE")
#mxd.saveACopy(r"C:\Temp\Split MXD2.mxd")
del mxd


Runtime error 
Traceback (most recent call last):
  File "<string>", line 12, in <module>
  File "c:\program files (x86)\arcgis\desktop10.4\arcpy\arcpy\", line 182, in fn_
    return fn(*args, **kw)
  File "c:\program files (x86)\arcgis\desktop10.4\arcpy\arcpy\", line 1677, in MoveLayer
    assert move_c is not None, 'Did not find move layer.'
AssertionError: Did not find move layer.
0 Kudos
4 Replies
MVP Alum

Since you are making all lower case, I would try:

if == "taxparcels1":
# and
if == "sections":
Regular Contributor

I would have to rename my TOC layer to taxparcels1 & sections. Which i done, i didn't want to do that but that got me passed the error but nothing happened.

So that brings me to the other question, do i have to use mxd.saveACopy in order for the taxparcels1 layer to be on top of sections?

0 Kudos
MVP Honored Contributor

I think you're thinking about this backwards:

if == "Taxparcels1":

The layer you're inspecting is "lyr". It has a name, maybe "TaXpArCeLs1". The .lower() representation would be "taxparcels1". In any case, no will ever equal "Taxparcels1" because it has an uppercase letter.

MVP Alum

You should not have to rename your TOC layers.  The "" converts the layer name to lower case letters, and then it is compared to a specified lower case string.

If you want to save the changes you will need to use either:

# save the current mxd

# or save a copy
mxd.saveACopy(r"C:\Temp\Split MXD2.mxd")‍‍‍‍‍