Remove Layers

6566
16
Jump to solution
04-12-2015 02:59 AM
Yaron_YosefCohen
Occasional Contributor II

Hi  everyone,

i have mxd with 85 layers and i try to remove layers (with arcpy) that don't exist in the current data frame. i using this code:

import arcpy,os,sys,string
import arcpy.mapping
from arcpy import env

env.workspace = r"C:\Project"
for mxdname in arcpy.ListFiles('*.mxd'):
     print mxdname
     mxd = arcpy.mapping.MapDocument(r"C:\Project\\" + mxdname)
     df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
     for lyr in arcpy.mapping.ListLayers(mxd,"",df):
          if lyr in df.extent == False:
               arcpy.mapping.RemoveLayer(df, lyr)
               print 'RemoveLayer'     
     mxd.save()
del  mxd

but i get en error:

>>> 
Project.mxd

Traceback (most recent call last):
  File "C:/yaron/shonot/software/gis/tools/YARON_SCRIPTS/aaaaaaaaaaaaaa.py", line 15, in <module>
    if lyr in df.extent == False:
TypeError: argument of type 'Extent' is not iterable
>>> 

i don't know why my code doesn't work.

Thanks for any help.

16 Replies
Yaron_YosefCohen
Occasional Contributor II

you think maybe geonet help community would be more compatible to my question?

0 Kudos
Luke_Pinner
MVP Regular Contributor

The 'overlaps' method must return False if the dataframe extent is completely within/completely contains the layer extent. Try the 'disjoint' method instead. See the documentation - http://resources.arcgis.com/en/help/main/10.2/index.html#//018z00000072000000

Something like:

    for mxdname in arcpy.ListFiles('*.mxd'):

        print mxdname
        mxd = arcpy.mapping.MapDocument(os.path.join(env.workspace, mxdname))
        df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
        for lyr in arcpy.mapping.ListLayers(mxd, "" ,df):
              if df.extent.disjoint(lyr.getExtent()):
                  arcpy.mapping.RemoveLayer(df, lyr)
                  print lyr

        mxd.save()

    del  mxd
Yaron_YosefCohen
Occasional Contributor II

thanks Luke !! it works!!

0 Kudos
Yaron_YosefCohen
Occasional Contributor II

the code don't work with shape file - just with layer file

0 Kudos
Luke_Pinner
MVP Regular Contributor

Correct. A feature class does not have a "getExtent()" method like a layer does. You need the arcpy.Describe method and the extent property - i.e. arcpy.Describe(shapefile).extent

0 Kudos
GeorgeReece_Jr_
New Contributor III

I think Luke has the correct answer to this problem.