I try to count how many times the layer "frame" occurs in 3 MXD files.
The layer "frame" (this is the layer name in the table of contents) occur in "project1" (this is the first MXD file)- 1 time.
In "project2"- it occur 2 times.
In "project3"- it occur 3 times.
I'm using this python code:
import arcpy,os,sys,string
import arcpy.mapping
from arcpy import env
env.workspace = r"G:\desktop\Project"
counter = 0
for mxdname in arcpy.ListFiles("*.mxd"):
print mxdname
mxd = arcpy.mapping.MapDocument(r"G:\desktop\Project\\" + mxdname)
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
dfList = arcpy.mapping.ListDataFrames(mxd, "*")
for df in dfList:
for lyr in arcpy.mapping.ListLayers(mxd, "", df):
if lyr.name == "frame":
counter = counter + 1
print counter
mxd.save()
del mxd
But i get this incorrect result:
>>>
project1.mxd
1
project2.mxd
4
project3.mxd
6
>>>
What am I doing wrong?
2 Answers 2
You should reset your counter
variable to 0 every time you iterate over a new mxd, otherwise counter
will count the cumulative occurences of 'frame' layers. Create a new counter
variable for each iterated mxd by moving it inside the for loop (it will overwrite the previous one):
import arcpy,os,sys,string
import arcpy.mapping
from arcpy import env
env.workspace = r"G:\desktop\Project"
for mxdname in arcpy.ListFiles("*.mxd"):
counter = 0
print mxdname
mxd = arcpy.mapping.MapDocument(r"G:\desktop\Project\\" + mxdname)
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
dfList = arcpy.mapping.ListDataFrames(mxd, "*")
for df in dfList:
for lyr in arcpy.mapping.ListLayers(mxd, "", df):
if lyr.name == "frame":
counter = counter + 1
print counter
mxd.save()
del mxd
As @GISGe says, you need to reset the counter inside the loop.
Also, instead of
for lyr in arcpy.mapping.ListLayers(mxd, "", df):
if lyr.name == "frame":
counter = counter + 1
You could 1) use the wildcard argument in ListLayers, and 2) just check the length of the returned list.
counter += len(arcpy.mapping.ListLayers(mxd, "frame", df)
I'm not sure what this line is doing btw, as df is overwritten in the loop below it.
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]