Saturday 28 September 2019

How to insert layer excluding MXD files using arcpy?


I'm working on 24 MXD files. Several maps include "roads" layer in them, the other maps don't have this layer. I'm trying to add "roads" layer to all the maps that do not have this layer by using this code:


import arcpy,os,sys,fnmatch
from arcpy import env

env.workspace = r"G:\desktop\Project"
insertLayer = arcpy.mapping.Layer(r"G:\desktop\Project\layers\roads.lyr")

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]
refLayer = arcpy.mapping.ListLayers(mxd, "residence", df)[0]
for lyr in arcpy.mapping.ListLayers(mxd, "" ,df):
if 'roads' not in lyr:
arcpy.mapping.InsertLayer(df, refLayer, insertLayer, "BEFORE") # BEFORE\ AFTER

mxd.save()
counter = counter + 1

del mxd
print counter

and this is the error i get:


 >>> 
landUse.mxd
Traceback (most recent call last):

File "G:/desktop/y/yaron/shonot/software/---gis---/tools/YARON_SCRIPTS/aaaaaaaaaaaaaaaaa.py", line 18, in
if 'roads' not in lyr:
File "C:\Program Files (x86)\ArcGIS\Desktop10.3\ArcPy\arcpy\arcobjects\mixins.py", line 361, in __iter__
self.layers
AttributeError: LayerObject: Get attribute layers does not exist
>>>

UPDATE:


I added this code line:


  if 'roads' not in lyr.name:


and now 'roads' layer has been added several times (each map) to all maps no matter if they contain 'roads' layer or not.



Answer



Rather than looping through the layers, you can use python's filter function to determine if the roads layer is present.


So, replace


for lyr in arcpy.mapping.ListLayers(mxd, "" ,df):
if 'roads' not in lyr:
arcpy.mapping.InsertLayer(df, refLayer, insertLayer, "BEFORE") # BEFORE\ AFTER

with



if not filter(lambda x: 'roads' in x.name, arcpy.mapping.ListLayers(mxd, "" ,df)):  
arcpy.mapping.InsertLayer(df, refLayer, insertLayer, "BEFORE") # BEFORE\ AFTER

Update: If you don't want to use lambdas, you can set a flag in the loop then insert the layer afterwards


has_roads = False
for lyr in arcpy.mapping.ListLayers(mxd, "" ,df):
if 'roads' in lyr.name:
has_roads = True
if not has_roads:
arcpy.mapping.InsertLayer(df, refLayer, insertLayer, "BEFORE") # BEFORE\ AFTER

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...