Hello, I do not know why the following python script does not work and cause a change of the layer's name (from 'States' to 'Stany'). After running the script I have received the message:" script returned exit code 0". Any suggestions? Thank you.
import arcpy.mapping
mxd = arcpy.mapping.MapDocument("F:/DSW/Using_ArcGIS_Desktop/MexicoPopulationDensity.mxd")
for df in arcpy.mapping.ListDataFrames(mxd):
if (df.name == 'States'):
layers = arcpy.mapping.ListLayers(mxd,'Stany',df)
Yes, I have read this link, but I could not find there the answer to my problem. This is the layout view:
As Joshua says, your df name is wrong.
I would use something like
df = arcpy.mapping.ListDataFrames(mxd, "")[0] or df = arcpy.mapping.ListDataFrames(mxd, "Mexico")[0]
and then no need for if df,name == , just use
layers = arcpy.mapping.ListLayers(mxd,'states',df)
Thank you Anthony for your message.
I have changed my code into the following;
import arcpy.mapping
mxd = arcpy.mapping.MapDocument("CURRENT")
df=arcpy.mapping.ListDataFrames(mxd,"Mexico")[0]
layers = arcpy.mapping.ListLayers(mxd,'states',df)
but there is nothing about changing the name of a feature class from 'states' to 'stany', so the result is still the same...
Don't I need to use for..if clause in order to change the name of a feature class?
Like a lot of things, there are many ways to achieve what you want.
layers = arcpy.mapping.ListLayers(mxd,'states',df)
will return a list of all layers named states, so you could loop through it to change the name
for lyr in layers:
lyr.name = "stany"
However if there is only one layer likely to be called states in the mxd, a shorthand way of achieving this is
lyr = arcpy.mapping.ListLayers(mxd,'states',df)[0]
lyr.name = "stany"
Doing an if == is useful if you are wanting to loop through many layers of differing names. eg
layers = arcpy.mapping.ListLayers(mxd,'',df)
for lyr in layers:
if lyr.name == "states":
lyr.name = "stany"
elif lyr.name == "Lakes":
lyr.name = "Lakey"
or to do more complex 'stuff' with name matches than the ListLayers wildcard parameter allows, such as ignoring case.
if lyr.name.lower() == "states":
Finally, if you are doing this with the mxd open, add in the following to see the changes on screen
arcpy.RefreshTOC()
And save the mxd if required
mxd.save()
Thank you very much for your help
Please mark Anthony's response Correct if it answered your question. That way, it lets others know the question has been answered.