Sunday, 7 July 2019

Finding layer file used to add layers to MXD in ArcPy?



I work with layer that located in G:\PROJECTS\bneyAyish\gis\lyr\New File Geodatabase.gdb\polygon, and I created a layer file and located it in G:\PROJECTS\bneyAyish\gis\lyr under the name "indisLabel":


enter image description here


I added the layer file "indisLabel" to some of the MXD files and after that i used this code in order to see if this code will find all the maps that have this specific layer file:


import arcpy  
from arcpy import mapping as m
from os import path, walk

root_directory = r"G:\PROJECTS\bneyAyish\gis"
path_to_find = r"G:\PROJECTS\bneyAyish\gis\lyr\indisLabel.lyr"
def FindMaps(root_directory, path_to_find):

maps = []
for root, dirnames, filenames in walk(root_directory):
for fname in [f for f in filenames if f.endswith(".mxd")]:
mxdPath = path.join(root, fname)
if not path.isfile(mxdPath):
print "didn't found"
continue

mxd = m.MapDocument(mxdPath)
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]

for df in m.ListDataFrames(mxd):
for lyr in m.ListLayers(mxd, data_frame=df):
if lyr.supports("DATASOURCE"):
if lyr.dataSource == path_to_find:
print(mxdPath)
maps.append(mxdPath)
return maps
FindMaps(root_directory, path_to_find)

And it doing nothing:



>>> ================================ RESTART ================================
>>>
>>>

Answer



Your path_to_find variable is a full pathname to a *.lyr file.


You are then using the value of this variable to search for any layers with that as their source.


However, any layers added using this layer file will not have the layer file as their source.


A layer file can be in one folder but the dataset it is linking to can be in another, so testing the path of your layer file is not testing the data source path.


You could try setting the variable path_to_find to be the data source instead i.e.in your example it would be G:\PROJECTS\bneyAyish\gis\lyr\New File Geodatabase.gdb\polygon.


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...