Need Help with Code to List Layers and their Data Frames

350
1
05-19-2014 11:03 AM
DevinDePonte
New Contributor II
Hey all!

I am relatively new to the forums (and Python) so please let me know if I am asking a question that is already answered elsewhere.

Basically I am trying to edit a code given to me in order to list all the layers in my .mxd and correlate them to the data frame they are in.  Right now I have this code:

import arcpy
mxd = arcpy.mapping.MapDocument(r"FILENAME")
for lyr in arcpy.mapping.ListLayers(mxd):
    if lyr.supports("DATASOURCE"):
        print "Layer: " + lyr.name + "  Source: " + lyr.dataSource


Which was given to me, I have tried a few different options in the past week on my spare time to see if I could get it working to no luck yet.  Is this code editable to the point of being able to also show the data frame name along with what information is already being shown?

Any help/guide in the right direction will be more than appreciated. Thanks!
Tags (2)
0 Kudos
1 Reply
markdenil
Occasional Contributor III
First off:  when typing code in the forum window, wrap it in code tags
The pound button (#) in the formatting buttons will insert the tags for you.
Whitespace is important with python, and without the code tags, leading white space is weeded out.

Next, you want a path name to your mxd, and the full mxd file name.
If this script is to run inside arcMap (in the python window, for example),
then you can just use the keyword "CURRENT" instead of a full path.

If you have multiple data frames, you may want to cycle through them,
getting the layers from each. Use ListDataFrames

import arcpy
mxd = arcpy.mapping.MapDocument(r"c:\workDir\FILENAME.mxd")
dfList = arcpy.mapping.ListDataFrames(mxd)

for df in dfList:
    lyrList = arcpy.mapping.ListLayers(mxd, "", df):
    print "Data Frame: ", df.name
    for lyr in lyrList:
        if lyr.supports("DATASOURCE"):
            source = lyr.dataSource
        else:
             source = "undefined"

        print "Layer: " + lyr.name + " Source: " + source
0 Kudos