2

Running ArcMap 10.1

So, I have a bunch of layers that all have the same name. I'm trying to rename them so that they have names that actually mean something.

Everything runs fine until it is time for the names to actually change. Nothing happens, and I don't know why.

Here is my code:

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Users\User\Documents\GISProj\Map6.mxd")
names=['Alexander','Avery','Buncombe','Burke','Caldwell','Cleveland','Durham','Gaston','Henderson','Jackson','Macon','Orange','Polk','Rutherford','Stokes','Surry','Transylvania','Watauga','Wilkes']
names.reverse()
cntys=arcpy.mapping.ListLayers(mxd,'slope')
for c in cntys:
    c.name=names[cntys.index(c)]
arcpy.RefreshTOC()

after I run it, I can see that cntys returns

[<map layer u'Wilkes'>, <map layer u'Watauga'>, <map layer u'Transylvania'>, <map layer u'Surry'>, <map layer u'Stokes'>, <map layer u'Rutherford'>, <map layer u'Polk'>, <map layer u'Orange'>, <map layer u'Macon'>, <map layer u'Jackson'>, <map layer u'Henderson'>, <map layer u'Gaston'>, <map layer u'Durham'>, <map layer u'Cleveland'>, <map layer u'Caldwell'>, <map layer u'Burke'>, <map layer u'Buncombe'>, <map layer u'Avery'>, <map layer u'Alexander'>]

just like it should. But the actual layer names in the TOC don't change, even when I save, close, and reopen the map.

From what I'm looking at here:https://geonet.esri.com/thread/43148 and here:Use ArcPy to rename MXD layers it should work, but it doesn't. Whats up with this?

1 Answer 1

1

I think there are two ways to fix this:

  1. If you have "C:\Users\User\Documents\GISProj\Map6.mxd" open then, instead of referencing r"C:\Users\User\Documents\GISProj\Map6.mxd", use "CURRENT"; or
  2. Run the code with ArcMap closed but include mxd.save() as its last line - the arcpy.RefreshTOC() is not then needed.

I think of using

mxd = arcpy.mapping.MapDocument(r"C:\Users\User\Documents\GISProj\Map6.mxd")

as being like running a separate mapping instance from the one you have open in ArcMap which is "CURRENT".

3
  • For 1, I believe this is correct - c is a layer object, and cntys is a list of layers. index returns the integer index of an item in a list. For 2, I cleaned up the code a bit before I posted to make it more readable, but I didn't catch the name change. I don't think the problem is in the for loop, though. When I print the list cntys, it shows what I expect: a list of layer objects with the correct names.
    – user41428
    Dec 6, 2014 at 10:06
  • Also, there weren't any errors thrown. The problem is that the name changes refuse to institute themselves in the map.
    – user41428
    Dec 6, 2014 at 10:09
  • I was wrong about the index but I think I just spotted what is astray and so I am going to change my answer.
    – PolyGeo
    Dec 6, 2014 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.