0

Is it possible to change the describe nameString of a .lyr file using arcpy? The name of the .lyr file is correct, but when the .lyr is brought into an .mxd the display name (nameString) is different, and I would like to make them the same.

I'm looking to remove "_clip" from .lyrs that have it in their nameString:

import arcpy
import os

workspace = r"C:\..."
lyrs = []

walk = arcpy.da.Walk(workspace)

for dirpath, dirnames, filenames in walk:
    for filename in filenames:
        lyrs.append(os.path.join(dirpath, filename))

for lyr in lyrs:
    desc = arcpy.Describe(lyr)

    if "_clip" in desc.nameString[-5:]:
        print desc.nameString

nameStrings are read only - https://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-functions/layer-properties.htm

Using ArcGIS Desktop 10.5

5
  • 2
    Can't you just edit the layer name when it's loaded in the map then save out a new layer file overwriting the old one, then you would not have to do any of this?
    – Hornbydd
    Feb 19, 2020 at 18:46
  • In my case, no. This is part of a larger tool being used in my organization, and that request wouldn't be reasonable.
    – Pdavis327
    Feb 19, 2020 at 18:49
  • With your new amended code, what is unsuccessful about it? You don't say if there is an error message or it runs doing some partial changes or a straight up nothing happens?
    – Hornbydd
    Feb 20, 2020 at 13:26
  • It completes successfully. When i then drag the layer into an .mxd it still has the original name.Nothing happens. I confirmed that the layers are going into the loop properly, and "lyr_in" is being assigned the layer.
    – Pdavis327
    Feb 20, 2020 at 15:13
  • Is lyr that is coming out of lyrs the layerfile so it should be something like c:\temp\data\geology.lyr?
    – Hornbydd
    Feb 20, 2020 at 19:00

2 Answers 2

2

Create a layer object from your file path. You can update and save the layer file using layer object properties and methods.

>>> lyrFl = r"C:\test.lyr" 
>>> arcpy.Describe (lyrFl).nameString #check name with describe
u'mains'
>>> lyr = arcpy.mapping.Layer (lyrFl) #create layer object
>>> lyr.name
u'mains'
>>> lyr.name = "newname" #change name
>>> lyr.save () #save layer
>>> lyr = arcpy.mapping.Layer (lyrFl) #test to see if it worked
>>> lyr.name
u'newname'
0
1

I think you need to load the layer file into a map document, adjust the layer name and then overwrite the layer file. This could be achieved via the layer object via the mapping module. Currently your code is trying to manipulate the layer file outside the map document and accessing a property which as you have discovered is read only.

Your Answer

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

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