2

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?

Matt
1,69218 silver badges24 bronze badges
asked Nov 30, 2016 at 10:32

2 Answers 2

4

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
answered Nov 30, 2016 at 10:37
3

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]
answered Nov 30, 2016 at 10:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.