3

I have the following code. I want to see if a layer name exists within a map document, not if the shapefile exists in the directory. If I copy paste into the python window within ArcMap works fine. IE. Prints: True

If I run the program as a stand-alone script it does not work? Prints False when should print True I have code the sets up the mxd and dataframe.

if arcpy.Exists("project_aoa") == True:
 print("TRUE")
elif arcpy.Exists("project_aoa") == False:
 print("FALSE")

These layers are withing a group layer should this matter?

project_aoa is a shapefile.

EDITED:

I ended up doing this:

for item in mxds:
 mxd = arcpy.mapping.MapDocument(r"{0}".format(item))
 df=arcpy.mapping.ListDataFrames(mxd,"Project Area")[0]
 for lyr in arcpy.mapping.ListLayers(mxd, "project_aoa", df):
 if lyr.name == "project_aoa":
 print("True")
 else:
 print ("False")
asked Jul 16, 2012 at 20:44
0

3 Answers 3

6

arcpy.Exists only works on datasets, so it will only return whether or not a file, feature class, dataset, or feature layer (among other items) exists. Layers in an mxd are not any of those things - they're a separate class, and they reference a dataset themselves.

SO, why does it work in the Python window, but not in the standalone script? Because in ArcMap, the TOC layers are ALSO feature layers of the same dataset (effectively - they have to be in order to be displayed). arcpy.Exists("project_aoa") returns true because in addition to being a map layer, there is ALSO a feature layer of that name for it to find. In a standalone script where you open an mxd, that same thing doesn't occur, so you need to iterate over the layers (unfortunately) to find it.

answered Jul 17, 2012 at 20:59
3

This code works for me:

mxd = arcpy.mapping.MapDocument(mxd_Path)
for lyr in arcpy.mapping.ListLayers(mxd):
 print lyr
 print arcpy.Exists(lyr.dataSource) 

for further info see this

nicksan
1,7161 gold badge12 silver badges22 bronze badges
answered Jul 17, 2012 at 14:09
2

I'm not sure you need to test equality here. The exists method should return true or false on it's own.

Try this:

if arcpy.Exists("project_aoa"):
 print "True"

Also, you can shorten the code a smidge by using an else statement instead of an elif -- just splitting hairs though.

answered Jul 16, 2012 at 21:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.