Layer On/Off Visibility using a Python list

5864
3
10-15-2012 01:11 PM
KyleGallagher
New Contributor III
I am trying to export multiple maps through one mxd, toggling on/off specific layers for specific maps.  My thought is that if I create a list with the string layer names in it, I should be able to cycle through the TOC and turn on those layers, otherwise turn it off.  There seems to be a problem once the for loop terminates checking the first list item.  Here is the error I am getting:

AttributeError: LayerObject: Error in accessing Visible property
referencing this line from the code below: lyr.visible = False

Note that the mxd and df variables have been defined in code not included.

list = ["Layer1", "Layer2", "Layer3", "Layer4", "Layer5", "Layer6"]
for item in list:
[INDENT]for lyr in arcpy.mapping.ListLayers(mxd, "", df):[/INDENT]
[INDENT][INDENT]if item in lyr.name:[/INDENT][/INDENT]
[INDENT][INDENT][INDENT]lyr.visible = True[/INDENT][/INDENT][/INDENT]
[INDENT][INDENT][INDENT]print lyr.name + " turned ON"[/INDENT][/INDENT][/INDENT]
[INDENT][INDENT]else:[/INDENT][/INDENT]
[INDENT][INDENT][INDENT]lyr.visible = False[/INDENT][/INDENT][/INDENT]

[INDENT][INDENT][INDENT]print lyr.name + " turned OFF"[/INDENT][/INDENT][/INDENT]

[INDENT]arcpy.RefreshActiveView[/INDENT]


Any thoughts?  Thanks!
Tags (2)
0 Kudos
3 Replies
T__WayneWhitley
Frequent Contributor
Use the 2nd param to your advantage.  If you plug in each unique 'item' of your list on looping, the index will always be [0].  See this (scroll down or search for 'turn on visibility...' section):
http://blogs.esri.com/esri/arcgis/2010/12/14/combining-data-driven-pages-with-python-and-arcpy-mappi...
0 Kudos
T__WayneWhitley
Frequent Contributor
Actually I see another error, but this only points out the code is a little difficult to read... More succinct code is at the blog link I sent on the previous post.  I'm not certain 'if item in layer.name' is executing properly...maybe do this instead:

(after 'item in list' line):
lyr = arcpy.mapping.ListLayers(mxd, item, df)[0]
lyr.visible = True


EDIT:  I thought about this again, and if you want to toggle on what's in the list; off what isn't, then I don't see why you don't do it the following way? (ListLayers returns layer objects in a list, so simply loop the list, get the layer name, and compare the string to that in your 'list' of strings):

for lyr in arcpy.mapping.ListLayers(mxd, "", df):
       if lyr.name in list:
            lyr.visible = True
       else:
            lyr.visible = False
0 Kudos
KyleGallagher
New Contributor III
Worked like a charm! Thanks!
0 Kudos