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)
maybe you need to mxd.save() before the changes persist
Unfortunately, it doesn't help.
ok, add an else portion to the if ... python is exiting without doing anything
if ...
do stuff
else:
print('not found')
My python code looks like this now:
for df in arcpy.mapping.ListDataFrames(mxd):
if (df.name == 'states'):
layers = arcpy.mapping.ListLayers(mxd,'Stany',df)
else:
print('not found')
mxd.saveACopy
I have received the message 'not found', but the layer is the project folder.
I suppose that the problem is associated with refreshing.
As I have changed the name of shp file -> from States to states and use python to print the name of the layers, I have received the same result as BEFORE the change. So instead of:
Cities
states
Lakes
Mexico Bnd
Central America Bnd
USA Bnd, I have got:
Cities
Lakes
Mexico Bnd
States
Central America Bnd
USA Bnd
Could you please give me advice how to solve this problem?
is mxd defined as "Current" somewhere? that seems to be the piece that is missing for me... Did you read the link I sent you? The project has to be named as on disk or if you are working interactively, then with the Current keyword. Also, you are in source view in the table of contents, ... go to the data view (to the left of your current selection) to ensure that the layer is named "states" and not "States"
This is the whole python code:
import arcpy.mapping
mxd = arcpy.mapping.MapDocument("F:/DSW/Using_ArcGIS_Desktop/MexicoPopulation.mxd")
print mxd.title
layers = arcpy.mapping.ListLayers(mxd)
for lyr in layers:
print lyr.name
for df in arcpy.mapping.ListDataFrames(mxd):
if (df.name == 'states'):
layers = arcpy.mapping.ListLayers(mxd,'Stany',df)
else:
print('not found')
mxd.saveACopy
I do not use CURRENT keyword, because I do not run a script from ArcGIS Python window, but from the PythonWin. Instead of that I put the correct pathfile of the *.mxd file and all *shp. files, which are included in this project.
The layer name is states. And now after loding the script once again, I have received the correct answer.
Unfortunately, the problem with changing the name of the layer states to Stany still remains...
Have you got any other ideas?
Yes, I have read this link, but I could not find there the answer to my problem.
Your data frame name is "Mexico," you are never going to find your 'states' layer if it is nested within your df.name == 'states' statement.